欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

【文件上传】smartupload工具包的使用方法(附Demo)

程序员文章站 2022-06-18 13:58:38
...

smartupload是一个常用的文件上传的工具包

jar包链接:
链接:https://pan.baidu.com/s/1WJeO2HQAm-Mq7pqf81OMjA
提取码:mr92

O、smartupload常用方法

【文件上传】smartupload工具包的使用方法(附Demo)

一、配置index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
  </head>
  <body>
    <form action="/upload" method="post" enctype="multipart/form-data">
      名称:<input type="text" name="uname"><br>
      文件:<input type="file" name="myfile"><br>
      <input type="submit" value="上传">
    </form>
  </body>
</html>

二、配置Servlet

@WebServlet(value = "/upload")
public class UploadServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1.创建对象
        SmartUpload smartUpload = new SmartUpload();
        //2.初始化
        PageContext pageContext = JspFactory.getDefaultFactory().getPageContext(this, req, resp, null, false, 1024 * 5, true);
        smartUpload.initialize(pageContext);
        //3.设置编码方式
        smartUpload.setCharset("utf-8");
        //4.上传
        try {
            smartUpload.upload();
        } catch (SmartUploadException e) {
            e.printStackTrace();
        }
        //5.保存文件
        File file = smartUpload.getFiles().getFile(0);
        //6.得到文件的基本信息
        String fileName = file.getFileName();
        //指定服务器保存文件的路径
        String url = "uploadfile/" + fileName;
        //保存文件
        try {
            file.saveAs(url,File.SAVEAS_VIRTUAL);
        } catch (SmartUploadException e) {
            e.printStackTrace();
        }
        //是否保存成功?---> 如果上传成功,则页面中显示该文件
        req.setAttribute("filename",fileName);
        //7.测试:除文件以外的内容如何获取?
        String uname = smartUpload.getRequest().getParameter("uname");
        System.out.println("uname=" + uname);
        //8.跳转页面
        req.getRequestDispatcher("success.jsp").forward(req,resp);
    }
}

注意:

(1)此时如果表单中有其他数据时,不能通过request直接获取,需要通过SmartUpload对象获取。

 String name=su.getRequest().getParameter("bookName");

并且该代码要在SmartUpload操作完成后添加。

(2)解决乱码:

 new String(name.getBytes("GBK"),"utf-8") //注:斜杠方向:/

(3)getPageContext

【文件上传】smartupload工具包的使用方法(附Demo)

【文件上传】smartupload工具包的使用方法(附Demo)

三、跳转显示

<body>
    <h1>success.jsp</h1>
    <img src="uploadfile/${filename}">
</body>

四、上传结果

【文件上传】smartupload工具包的使用方法(附Demo)

五、写在最后

不明之处可以咨询博主。 看到了会回复。