UploadStream.java 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. package com.kmall.common.fileserver.fastdfs;
  2. import java.io.IOException;
  3. import java.io.InputStream;
  4. import java.io.OutputStream;
  5. /**
  6. * Upload file by stream
  7. *
  8. * @author zhouzezhong & Happy Fish / YuQing
  9. * @version Version 1.11
  10. */
  11. public class UploadStream implements UploadCallback {
  12. private InputStream inputStream; //input stream for reading
  13. private long fileSize = 0; //size of the uploaded file
  14. /**
  15. * constructor
  16. *
  17. * @param inputStream input stream for uploading
  18. * @param fileSize size of uploaded file
  19. */
  20. public UploadStream(InputStream inputStream, long fileSize) {
  21. super();
  22. this.inputStream = inputStream;
  23. this.fileSize = fileSize;
  24. }
  25. /**
  26. * send file content callback function, be called only once when the file uploaded
  27. *
  28. * @param out output stream for writing file content
  29. * @return 0 success, return none zero(errno) if fail
  30. */
  31. public int send(OutputStream out) throws IOException {
  32. long remainBytes = fileSize;
  33. byte[] buff = new byte[256 * 1024];
  34. int bytes;
  35. while (remainBytes > 0) {
  36. try {
  37. if ((bytes = inputStream.read(buff, 0, remainBytes > buff.length ? buff.length : (int) remainBytes)) < 0) {
  38. return -1;
  39. }
  40. } catch (IOException ex) {
  41. ex.printStackTrace();
  42. return -1;
  43. }
  44. out.write(buff, 0, bytes);
  45. remainBytes -= bytes;
  46. }
  47. return 0;
  48. }
  49. }