文件上传和下载

导入两个jar包
在这里插入图片描述

前端

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<form method="post" enctype="multipart/form-data" action="/Upload.do">
    上传文件:<input type="file" name="file" id="file">
    <input type="text" name="age" id="d1">
    <input type="submit" value="文件上传">
</form>
<a href="/download?filename=13.jpg" name="13.jpg">13.jpg</a>
</body>
</html>

上传


@WebServlet("/Upload.do")
public class UpLoad extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置工厂的存储区域
        DiskFileItemFactory diskFileItemFactory1 = new DiskFileItemFactory(10240, (File) this.getServletConfig().getServletContext().getAttribute("javax.servlet.context.tempdir"));
        //创建文件上传处理器
        ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory1);
        //解析请求
        List list = null;
        try {
            list = servletFileUpload.parseRequest(req);
            //获取集合的迭代器
            Iterator<FileItem> iterator = list.iterator();
            while (iterator.hasNext()) {
                FileItem next = iterator.next();
                //处理表单项
                if (next.isFormField()) {
                    //普通表单项(比如密码,多选框)

                } else {
                    //获取上传文件名字
                    String string = next.getName();
                    //一般上传服务器,都保存在固定的文件中
                    File file = new File("e:/Temp", string);
                    //next.write(file);
                    FileUtils.copyInputStreamToFile(next.getInputStream(),file);
                }
            }

        } catch (FileUploadException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

下载

@WebServlet("/download")
public class DownLoad extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取文件名字
        String filename = req.getParameter("filename");
        //设置响应头内容类型为下载,保存在本地
        resp.setContentType("application/x-msdownload");
        //设置响应头,让下载的过程由用户干涉,还可以保证文件名称
        resp.addHeader("content-disposition","attachment;filename="+filename);
        //获取服务器文件路径
        File src=new File("e:/Temp",filename);

        FileUtils.copyFile(src,resp.getOutputStream());
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值