JAVAWEB(7)文件上传

目录

使用smartupload.jar实现文件上传

文件下载 


 使用smartupload.jar实现文件上传

  • jar包添加到项目中:smartupload.jar
  • 准备上传的页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>文件上传</title>
  </head>
  <body>
    <h1>index.jsp</h1>
    <form action="uploadFile" method="post" enctype="multipart/form-data">
      姓名<input type="text" name="uname"><br/>
      图片<input type="file" name="pic"><br/>
      <input type="submit" value="上传">
    </form>
  </body>
</html>
:
(1)form 标签中要添加 enctype 属性
(2) 提交方式必须是 post
  • 开始获取数据,保存文件
实例代码:
import com.jspsmart.upload.File;
import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspFactory;
import javax.servlet.jsp.PageContext;
import java.io.IOException;

/**
 * @Author: xuliushen
 * @Description:
 * @Date Created in 2021-09-23 17:46
 * @Modified by :
 */
@WebServlet(urlPatterns = "/uploadFile")
public class FileUploadServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws 
ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws 
ServletException, IOException {
        try {
            //1.创建上传文件的对象
            SmartUpload file = new SmartUpload();
            //2.初始化上传操作
            PageContext pageContext = JspFactory.getDefaultFactory()
                    .getPageContext(this,req,resp,null,false,1024,true);
            file.initialize(pageContext);
            //2.1设置编码
            file.setCharset("UTF-8");
            //3.上传
            file.upload();

            //4.获得文件信息
            //文字信息,通过file得到request
            String uname = file.getRequest().getParameter("uname");
            System.out.println("uname"+uname);
            File info = file.getFiles().getFile(0);
            String fileName = info.getFileName();
            String contentType = info.getContentType();

            //5.指定上传的路径
            String upLoadPath =  "/uploadfiles/"+fileName;
            //6.保存到指定位置;
            info.saveAs(upLoadPath,File.SAVEAS_VIRTUAL);

            //7.跳转到成功页面
            req.setAttribute("filename",fileName);
            req.getRequestDispatcher("success.jsp").forward(req,resp);
        } catch (SmartUploadException e) {
            e.printStackTrace();
        }

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

smartupload 常用方法

文件下载 

<%--
  Created by IntelliJ IDEA.
  User: 34431
  Date: 2021/9/23
  Time: 18:39
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>success.jsp</title>
</head>
<body>
  <h1>success.jsp</h1>
  <a href="${pageContext.request.contextPath}/downloadFile?filename=${filename}">
下载</a><br/>
  <img src="uploadfiles/${filename}">

</body>
</html>

 

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * @Author: xuliushen
 * @Description:
 * @Date Created in 2021-09-23 18:59
 * @Modified by :
 */
@WebServlet(urlPatterns = "/downloadFile")
public class FileDownloadServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String filename = req.getParameter("filename");
        String path = "/uploadfiles/"+filename;
        //设置响应的头信息和相应类型
        resp.setContentType("application/octet-stream");
        resp.addHeader("Content-Disposition","attachment;filename="+
                URLEncoder.encode(filename, StandardCharsets.UTF_8));
        //跳转页面
        req.getRequestDispatcher(path).forward(req,resp);
        //清空缓存区
        resp.flushBuffer();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

hnu哈哈

请接受直女的么么哒????

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

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

打赏作者

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

抵扣说明:

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

余额充值