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

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

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

O、smartupload常用方法

在这里插入图片描述

一、配置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

在这里插入图片描述

在这里插入图片描述

三、跳转显示

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

四、上传结果

在这里插入图片描述

五、写在最后

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

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Cry丶

如果觉得有帮助的打个赏吧。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值