Nie możesz wybrać więcej, niż 25 tematów Tematy muszą się zaczynać od litery lub cyfry, mogą zawierać myślniki ('-') i mogą mieć do 35 znaków.

HelloServlet.java 5.6KB

5 miesięcy temu
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140
  1. package com.kso.test;
  2. import java.io.ByteArrayOutputStream;
  3. import java.io.FileOutputStream;
  4. import java.io.IOException;
  5. import java.io.InputStream;
  6. import java.util.HashMap;
  7. import java.util.List;
  8. import java.util.Map;
  9. import javax.servlet.ServletException;
  10. import javax.servlet.annotation.WebServlet;
  11. import javax.servlet.http.Cookie;
  12. import javax.servlet.http.HttpServlet;
  13. import javax.servlet.http.HttpServletRequest;
  14. import javax.servlet.http.HttpServletResponse;
  15. import javax.servlet.http.HttpSession;
  16. import org.apache.commons.fileupload.FileItem;
  17. import org.apache.commons.fileupload.FileItemFactory;
  18. import org.apache.commons.fileupload.FileUploadException;
  19. import org.apache.commons.fileupload.disk.DiskFileItemFactory;
  20. import org.apache.commons.fileupload.servlet.ServletFileUpload;
  21. @WebServlet({ "/HelloServlet" })
  22. public class HelloServlet extends HttpServlet {
  23. private static final long serialVersionUID = 1L;
  24. private static String s_fileName = "";
  25. ByteArrayOutputStream output;
  26. /**
  27. * 下载文件
  28. *
  29. * @param request
  30. * @param response
  31. * @throws ServletException
  32. * @throws IOException
  33. */
  34. protected void doGet(HttpServletRequest request, HttpServletResponse response)
  35. throws ServletException, IOException {
  36. String filename = request.getParameter("name");
  37. if (filename == null || filename.isEmpty()) {
  38. out.print("please set file name ");
  39. } else {
  40. // 假设文件都在服务的根目录下
  41. String realFileName = request.getServletContext().getRealPath("/") + filename;
  42. System.out.println(realFileName);
  43. // 实例化一个向客户端输出文件流
  44. OutputStream outputStream = response.getOutputStream();
  45. // 输出文件用的字节数组,每次向输出流发送600个字节
  46. byte b[] = new byte[600];
  47. // 要向客户端输出的文件
  48. File fileload = new File(realFileName);
  49. System.out.println(filename);
  50. String utf8filename = URLEncoder.encode(filename, "UTF-8");
  51. System.out.println(utf8filename);
  52. response.setHeader("Content-disposition", "attachment; filename=" + utf8filename);
  53. // 通知客户端:文件的MIME类型
  54. response.setContentType("application/msword");
  55. // 通知客户端:文件的长度
  56. long fileLength = fileload.length();
  57. String length = String.valueOf(fileLength);
  58. response.setHeader("Content-length", length);
  59. // 读取文件,并发送给客户端下载
  60. FileInputStream inputStream = new FileInputStream(fileload);
  61. int n = 0;
  62. while ((n = inputStream.read(b)) != -1) {
  63. outputStream.write(b, 0, n);
  64. }
  65. inputStream.close();
  66. outputStream.close();
  67. }
  68. }
  69. /**
  70. * 上传文件
  71. *
  72. * @param request
  73. * @param response
  74. * @throws ServletException
  75. * @throws IOException
  76. */
  77. protected void doPost(HttpServletRequest request, HttpServletResponse response)
  78. throws ServletException, IOException {
  79. request.setCharacterEncoding("utf-8");
  80. response.setContentType("text/html;charset=utf-8");
  81. System.out.println("添加任务");
  82. HttpSession session = request.getSession();
  83. Cookie[] cookies = request.getCookies();
  84. String value = "";
  85. try {
  86. DiskFileItemFactory factory = new DiskFileItemFactory();
  87. ServletFileUpload upload = new ServletFileUpload((FileItemFactory) factory);
  88. upload.setHeaderEncoding("UTF-8");
  89. List items = upload.parseRequest(request);
  90. boolean isOk = false;
  91. Map<Object, Object> param = new HashMap<>();
  92. for (Object object : items) {
  93. FileItem fileItem = (FileItem) object;
  94. if (fileItem.isFormField()) {
  95. System.out.println(fileItem.getFieldName() + ":" + fileItem.getString("utf-8") + ", size:"
  96. + fileItem.getSize());
  97. param.put(fileItem.getFieldName(), fileItem.getString("utf-8"));
  98. continue;
  99. }
  100. String fieldName = fileItem.getFieldName();
  101. // 必须要有文件名,需要客户端传参时注意
  102. String fileName = fileItem.getName();
  103. if (fileName.equals("blob"))
  104. if (param.containsKey("filename")) {
  105. fileName = param.get("filename").toString();
  106. } else if (param.containsKey("fileName")) {
  107. fileName = param.get("fileName").toString();
  108. }
  109. String filePath = request.getSession().getServletContext().getRealPath("/") + fileName;
  110. System.out.println(fieldName + ":" + filePath);
  111. FileOutputStream fileOut = new FileOutputStream(filePath);
  112. InputStream in = fileItem.getInputStream();
  113. byte[] buffer = new byte[1024];
  114. int len = 0;
  115. while ((len = in.read(buffer)) > 0) {
  116. fileOut.write(buffer, 0, len);
  117. }
  118. in.close();
  119. fileOut.close();
  120. response.setHeader("Content-disposition", "attachment; filename*=UTF-8''" + fileName);
  121. response.getWriter().write(fileName.concat("上传成功"));
  122. return;
  123. }
  124. } catch (FileUploadException e) {
  125. e.printStackTrace();
  126. }
  127. response.sendError(404, "no ssison");
  128. }
  129. }