使用smartupload.jar实现文件上传

1.将jar包添加到项目中:smartupload.jar

2.准备上传的页面

  1. <%--
  2. Created by IntelliJ IDEA.
  3. User: Administrator
  4. To change this template use File | Settings | File Templates.
  5. --%>
  6. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
  7. <html>
  8. <head>
  9. <title>$Title$</title>
  10. </head>
  11. <body>
  12. <form action="/upload" method="post" enctype="multipart/form-data">
  13. 名称:<input type="text" name="uname" ><br>
  14. 文件:<input type="file" name="myfile"><br>
  15. <input type="submit" value="上传">
  16. </form>
  17. </body>
  18. </html>

注:
(1)form标签中要添加enctype属性
(2)提交方式必须是post
(3).开始获取数据,保存文件

  1. package com.yhp.web;
  2. import com.jspsmart.upload.File;
  3. import com.jspsmart.upload.SmartUpload;
  4. import com.jspsmart.upload.SmartUploadException;
  5. import javax.servlet.ServletException;
  6. import javax.servlet.annotation.WebServlet;
  7. import javax.servlet.http.HttpServlet;
  8. import javax.servlet.http.HttpServletRequest;
  9. import javax.servlet.http.HttpServletResponse;
  10. import javax.servlet.jsp.JspFactory;
  11. import javax.servlet.jsp.PageContext;
  12. import java.io.IOException;
  13. /**
  14. * Administrator
  15. * uploadProject
  16. * 面向对象面向君 不负代码不负卿
  17. */
  18. @WebServlet(value = "/upload")
  19. public class UploadServlet extends HttpServlet {
  20. @Override
  21. protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  22. //1.创建对象
  23. SmartUpload smartUpload = new SmartUpload();
  24. //2.初始化
  25. PageContext pageContext = JspFactory.getDefaultFactory().getPageContext(this, req, resp, null, false, 1024 * 5, true);
  26. smartUpload.initialize(pageContext);
  27. //3.设置编码方式
  28. smartUpload.setCharset("utf-8");
  29. //4.上传
  30. try {
  31. smartUpload.upload();
  32. } catch (SmartUploadException e) {
  33. e.printStackTrace();
  34. }
  35. //5.保存文件
  36. File file = smartUpload.getFiles().getFile(0);
  37. //6.得到文件的基本信息
  38. String fileName = file.getFileName();
  39. //指定服务器保存文件的路径
  40. String url="uploadfile/"+fileName;
  41. //保存文件
  42. try {
  43. file.saveAs(url,File.SAVEAS_VIRTUAL);
  44. } catch (SmartUploadException e) {
  45. e.printStackTrace();
  46. }
  47. //是否保存成功?--->如果上传成功,则页面中显示该文件
  48. req.setAttribute("filename",fileName);
  49. //7.测试:除文件以外的内容如何获取
  50. String uname = smartUpload.getRequest().getParameter("uname");
  51. System.out.println("uname="+uname);
  52. //8.跳转页面
  53. req.getRequestDispatcher("/success.jsp").forward(req,resp);
  54. }
  55. }

注:
(1)此时如果表单中有其他数据时,不能通过request直接获取,需要通过SmartUpload对象获取
String name=su.getRequest().getParameter(“uname”);
并且该代码要在SmartUpload操作完成后添加
(2)解决乱码:
new String(name.getBytes(“GBK”),”utf-8”)
注:斜杠方向:/
注意:
image.png
image.png

smartupload常用方法

image.png