How to convert an InputStream to a DataHandler?

后端 未结 7 745
挽巷
挽巷 2020-12-05 07:20

I\'m working on a java web application in which files will be stored in a database. Originally we retrieved files already in the DB by simply calling getBytes o

7条回答
  •  独厮守ぢ
    2020-12-05 07:39

    An implementation of answer from "Kathy Van Stone":

    At first create helper class, which create DataSource from InputStream:

    public class InputStreamDataSource implements DataSource {
        private InputStream inputStream;
    
        public InputStreamDataSource(InputStream inputStream) {
            this.inputStream = inputStream;
        }
    
        @Override
        public InputStream getInputStream() throws IOException {
            return inputStream;
        }
    
        @Override
        public OutputStream getOutputStream() throws IOException {
            throw new UnsupportedOperationException("Not implemented");
        }
    
        @Override
        public String getContentType() {
            return "*/*";
        }
    
        @Override
        public String getName() {
            return "InputStreamDataSource";
        }
    }
    

    And then you can create DataHandler from InputStream:

    DataHandler dataHandler = new DataHandler(new InputStreamDataSource(inputStream))
    

    imports:

    import javax.activation.DataSource;
    import java.io.OutputStream;
    import java.io.InputStream;
    

提交回复
热议问题