24

I am getting inputstream from the Jsch channelSFTP like below.

   ChannelSftp channelSftp = (ChannelSftp) channel;
   InputStream input = channelsftp.get(unixPath); // unixPath is path to my file which is on SFTP server

I have to attach the file in the unixPath in the Spring JavaMail attachment. But when I see API of Spring JavaMail addAttachment() method it takes only InputStreamSource or Datasource. My problem is I am not able to get the InputStreamSource or Datasource from the inputStream which I am getting form SFTP channel.

How Can I get InputStreamSource or Datasource from the above InputStream?

2 Answers 2

54

From the documentation, InputStreamSource is an interface. One of its implementations is InputStreamResource, which has a constructor that takes in an InputStream. Here is the JavaDoc for it.

You should be able to setup your call as such:

addAttachment("Not porn", new InputStreamResource(inputStream));
4
  • 8
    For me exactly message.addAttachment("somefile name",new ByteArrayResource(IOUtils.toByteArray(channelSftp.get(unixPath)))); is working.Thanks anyway for the idea.
    – SRy
    Commented Nov 5, 2012 at 19:03
  • 6
    Note that this method does not allow for an inputStream that is already open.
    – Erica Kane
    Commented Feb 10, 2015 at 20:02
  • 8
    up for that awesome filename "not porn"
    – Daniel Bo
    Commented Apr 10, 2017 at 16:19
  • @SRy the method you showed worked perfectly for me. Thanks! Commented Dec 1, 2021 at 23:27
0

I host a Spring Boot application in Docker on my VPS. This code will work on a local system whilst developing in an IDE as well as if the .JAR-file is wrapped in a Docker image:

Example case:

I like to get a PDF. The PDf document is located at static/docs/not-a-porn.PDF.

1.) Wire the class ResourceLoader.

private final ResourceLoader resourceLoader;

public MyService(@Autowired ResourceLoader resourceLoader) {  
    this.resourceLoader = resourceLoader;
}

2.) Create a resource by pathOfAttachment (String).

String pathOfAttachment = "classpath:static/docs/not-a-porn.PDF"
Resource resource = this.resourceLoader.getResource(pathOfAttachment);

Resource is an interface that extends InputStreamSource as you can see in the documentation:

public interface Resource extends InputStreamSource

Source: org.springframework.core.io Link to documentation (click here)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.