java工具类------pad文件上传

雨点打透心脏的1/2处 2022-06-18 08:17 333阅读 0赞

1.在这里简单说一下这块的知识,因为在开发中遇到了,所以我整理了一下这块的知识,这边封装的是一个sevlet,所以一定要记着在web.xml中配置,这块不做过多赘述,下面直接说代码,代码如下:

  1. import java.awt.image.BufferedImage;
  2. import java.io.BufferedInputStream;
  3. import java.io.BufferedOutputStream;
  4. import java.io.File;
  5. import java.io.FileOutputStream;
  6. import java.io.IOException;
  7. import java.io.InputStream;
  8. import java.util.Calendar;
  9. import javax.servlet.ServletException;
  10. import javax.servlet.http.HttpServlet;
  11. import javax.servlet.http.HttpServletRequest;
  12. import javax.servlet.http.HttpServletResponse;
  13. import org.apache.commons.fileupload.FileItemIterator;
  14. import org.apache.commons.fileupload.FileItemStream;
  15. import org.apache.commons.fileupload.FileUploadException;
  16. import org.apache.commons.fileupload.disk.DiskFileItemFactory;
  17. import org.apache.commons.fileupload.servlet.ServletFileUpload;
  18. import org.apache.commons.fileupload.util.Streams;
  19. public class PdfUpload extends HttpServlet
  20. {
  21. private static final long serialVersionUID = 1L;
  22. private long size;
  23. private BufferedImage bsrc;
  24. private String type;
  25. public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{
  26. doPost(request,response); //将get请求和post请求统一发送给doPost处理 }
  27. }
  28. @Override
  29. public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
  30. {
  31. response.setCharacterEncoding("UTF-8");
  32. String returnMessage = "{status:'SUCCESS', data:''}";
  33. response.addHeader("Access-Control-Allow-Origin", "*");
  34. response.addHeader("Access-Control-Allow-Headers", "apptypeid,platformid,city,district,Content-Type, Authorization, Accept,X-Requested-With");
  35. response.addHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS");
  36. Calendar date = Calendar.getInstance();
  37. String saveDirectory = request.getSession().getServletContext().getRealPath("/upload"); // 在磁盘上保存的路径
  38. //String saveDirectory = "C:/Users/Administrator/Desktop";
  39. String saveUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/upload";
  40. String saveImgUrl = "";
  41. System.out.println("服务器的路径============="+saveDirectory);
  42. System.out.println("保存的路径============"+saveUrl);
  43. // 新建对应日期文件夹
  44. int iYear = date.get(Calendar.YEAR);
  45. saveDirectory += File.separator + iYear;
  46. saveUrl += "/" + iYear;
  47. int iMonth = date.get(Calendar.MONTH) + 1;
  48. saveDirectory += File.separator + iMonth;
  49. saveUrl += "/" + iMonth;
  50. int iDay = date.get(Calendar.DATE);
  51. saveDirectory += File.separator + iDay;
  52. saveUrl += "/" + iDay;
  53. File f = new File(saveDirectory);
  54. if (!f.isDirectory())
  55. {
  56. f.mkdirs();
  57. }
  58. if (ServletFileUpload.isMultipartContent(request))
  59. {
  60. DiskFileItemFactory dff = new DiskFileItemFactory();
  61. dff.setRepository(f);
  62. dff.setSizeThreshold(1024000);
  63. ServletFileUpload sfu = new ServletFileUpload(dff);
  64. FileItemIterator fii = null;
  65. try
  66. {
  67. fii = sfu.getItemIterator(request);
  68. }
  69. catch (FileUploadException e1)
  70. {
  71. e1.printStackTrace();
  72. }
  73. String saveFilePath = ""; // 图片地址
  74. try
  75. {
  76. int iIndex = 0;
  77. while (fii.hasNext())
  78. {
  79. FileItemStream fis = fii.next();
  80. try
  81. {
  82. if (!fis.isFormField() && fis.getName().length() > 0)
  83. {
  84. iIndex++;
  85. String saveFileName = iYear + "" + iMonth + "" + iDay + "" + date.get(Calendar.HOUR) + date.get(Calendar.MINUTE) + "" + date.get(Calendar.SECOND) + "-" + iIndex + ".pdf";
  86. saveFilePath = saveDirectory + File.separator + saveFileName;
  87. saveUrl += "/" + saveFileName;
  88. BufferedInputStream in = new BufferedInputStream(fis.openStream());
  89. FileOutputStream a = new FileOutputStream(new File(saveFilePath));
  90. BufferedOutputStream output = new BufferedOutputStream(a);
  91. Streams.copy(in, output, true);// 开始把文件写到你指定的上传文件夹
  92. String imgName = iYear + "" + iMonth + "" + iDay + "" + date.get(Calendar.HOUR) + date.get(Calendar.MINUTE) + "" + date.get(Calendar.SECOND) + "-" + iIndex+"jpg";
  93. saveImgUrl += saveDirectory + File.separator + imgName;
  94. System.out.println("完整路径================================="+saveUrl);
  95. System.out.println("图片路径================================="+saveImgUrl);
  96. PDF_to_JPGFuncation funcation = new PDF_to_JPGFuncation();
  97. PDF_to_JPGFuncation.tranfer(saveFilePath,
  98. saveImgUrl, 1);
  99. type = fis.getName().substring(fis.getName().lastIndexOf(".")).toLowerCase();
  100. }
  101. }
  102. catch (Exception e)
  103. {
  104. e.printStackTrace();
  105. returnMessage = "{\"status\":\"ERROR\",\"data\":\"\"}";
  106. }
  107. }
  108. if (returnMessage.indexOf("status:'SUCCESS'") > -1)
  109. {
  110. String savePath=saveFilePath.replaceAll("\\\\", "/");
  111. returnMessage = "{\"status\":\"OK\",\"data\":\"" + savePath + "\"}";
  112. }
  113. }
  114. catch (FileUploadException e)
  115. {
  116. e.printStackTrace();
  117. returnMessage = "{\"status\":\"ERROR\",\"data\":\"\"}";
  118. }
  119. //String urlEncoder = URLEncoder.encode(returnMessage, "utf-8");
  120. //String url = urlEncoder.replace("+", "%20");
  121. response.getWriter().println(returnMessage);
  122. }
  123. }
  124. private String readFileItem(FileItemStream fis) throws IOException
  125. {
  126. BufferedInputStream in = new BufferedInputStream(fis.openStream());
  127. byte[] bytes = readStream(in);
  128. if (bytes != null && bytes.length > 0)
  129. {
  130. try
  131. {
  132. return new String(bytes, 0, bytes.length);
  133. }
  134. catch (Exception e)
  135. {
  136. return "";
  137. }
  138. }
  139. return "";
  140. }
  141. private byte[] readStream(InputStream networkStream) throws IOException
  142. {
  143. byte[] bytes = new byte[100];
  144. byte[] bytecount = null;
  145. int n = 0;
  146. int ilength = 0;
  147. try
  148. {
  149. while ((n = networkStream.read(bytes)) >= 0)
  150. {
  151. if (bytecount != null)
  152. {
  153. ilength = bytecount.length;
  154. }
  155. byte[] tempbyte = new byte[ilength + n];
  156. if (bytecount != null)
  157. {
  158. System.arraycopy(bytecount, 0, tempbyte, 0, ilength);
  159. }
  160. System.arraycopy(bytes, 0, tempbyte, ilength, n);
  161. bytecount = tempbyte;
  162. if (n == -1)
  163. break;
  164. }
  165. }
  166. finally
  167. {
  168. networkStream.close();
  169. }
  170. return bytecount;
  171. }
  172. public void delFile(String filename)
  173. {
  174. File file = new File(filename);
  175. if (file.isFile() && file.exists())
  176. {
  177. file.delete();
  178. System.out.println("删除成功");
  179. }
  180. else
  181. {
  182. System.out.println("要删除的文件不存在");
  183. }
  184. }
  185. }

另外在这个方法中涉及到了一个类,代码如下:

  1. import java.awt.image.BufferedImage;
  2. import java.io.File;
  3. import java.io.FileOutputStream;
  4. import java.io.IOException;
  5. import java.util.Iterator;
  6. import javax.imageio.IIOImage;
  7. import javax.imageio.ImageIO;
  8. import javax.imageio.ImageReader;
  9. import javax.imageio.ImageWriter;
  10. import javax.imageio.stream.ImageOutputStream;
  11. import org.icepdf.core.exceptions.PDFException;
  12. import org.icepdf.core.exceptions.PDFSecurityException;
  13. import org.icepdf.core.pobjects.Document;
  14. import org.icepdf.core.pobjects.Page;
  15. import org.icepdf.core.util.GraphicsRenderingHints;
  16. public class PDF_to_JPGFuncation {
  17. public static final String FILETYPE_JPG = "jpg";
  18. public static final String SUFF_IMAGE = "." + FILETYPE_JPG;
  19. public static void tranfer(String filepath, String imagepath, float zoom)
  20. throws PDFException, PDFSecurityException, IOException {
  21. Document document = null;
  22. float rotation = 0f;
  23. document = new Document();
  24. document.setFile(filepath);
  25. BufferedImage img = (BufferedImage) document.getPageImage(0, GraphicsRenderingHints.SCREEN,
  26. Page.BOUNDARY_CROPBOX, rotation, zoom);
  27. Iterator iter = ImageIO.getImageWritersBySuffix(FILETYPE_JPG);
  28. ImageWriter writer = (ImageWriter) iter.next();
  29. File outFile = new File(imagepath + document.getNumberOfPages() + "." + FILETYPE_JPG);
  30. FileOutputStream out = new FileOutputStream(outFile);
  31. ImageOutputStream outImage = ImageIO.createImageOutputStream(out);
  32. writer.setOutput(outImage);
  33. writer.write(new IIOImage(img, null, null));
  34. }
  35. }

至此代码部分结束,上面用的jar文件是icepdf-core-4.3.3.jar,大家可以上网上搜索下载!

发表评论

表情:
评论列表 (有 0 条评论,333人围观)

还没有评论,来说两句吧...

相关阅读