Java中Jsp和Servlet上传和下载文件

上传:

前端页面:


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>file_up_test</title>
    <style type="text/css">
        #main {
            margin: 200px auto auto 200px;
        }
    </style>
</head>
<body>
<%--enctype:--%>
<%--1.application/x-www-form-urlencoded(默认)--%>
<%--2.multipart/form-data(二进制编码)--%>
<%--注意:使用二进制编码后Servlet无法使用req.getParam来获取参数--%>
<form action="${pageContext.request.contextPath}/FileUpTest" method="post" enctype="multipart/form-data">
    <div id="main">
        <div>
            选择用户名:
            <select id="selUser" name="userName" style="width: 120px; height: 30px">
                <option value="1">kobe</option>
                <option value="2">james</option>
            </select>
        </div>
        <br/>
        <div>
            选择文件:
            <%--这个约束没什么用--%>
            <input type="file" id="fileUp" name="fileUp" multiple="multiple" accept="image/*"
                   style="width: 300px; height: 30px"/>
        </div>
        <br/>
        <div>
            <input type="submit" value="提交" style="width: 120px; height: 30px"/>
        </div>
    </div>

</form>
</body>
</html>

后台代码:

package com.study.jsp.test;

import com.jdbc.library.common.FileUpUtil;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.*;
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.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;


@WebServlet("/FileUpTest")
public class FileUpTestServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        boolean isFileForm = ServletFileUpload.isMultipartContent(req);
        if (!isFileForm) {
            return;
        }
        FileUpUtil fileUpUtil = new FileUpUtil(req);
        //保存文件
        saveFile(req, fileUpUtil);
        //获取参数
        Map<String, String> paraMap = fileUpUtil.getFormPara();
        String userName = paraMap.get("userName");
        resp.getWriter().write(userName);
    }

    /**
     * 关于上传文件
     */
    private void aboutFile(HttpServletRequest req) {
        try {
            /*********************一.唯一标识**************************/
            //1.唯一标识1
            String dateStr = new SimpleDateFormat("yyyyMMddHHmmsssss").format(new Date());
            //2.唯一标识2
            //String uuId = UUID.randomUUID().toString();
            // (例如:美女.jsp)
            //3.唯一标识3
            //long milSeconds = new Date().getTime();
            /*********************二.文件扩展名**************************/
            //1.获取文件扩展名
            String fileName = "美女.jpg";
            //美女.jpg
            String name = FilenameUtils.getName(fileName);
            //美女
            String baseName = FilenameUtils.getBaseName(fileName);
            //jpg
            String extenName = FilenameUtils.getExtension(fileName);
            //美女.jpg
            String fullName = FilenameUtils.getFullPath(fileName);
            /*******************三.缓存大小和临时目录**************************/
            DiskFileItemFactory factory = new DiskFileItemFactory();
            //1.设置缓存大小(单位:字节 默认大小:10240字节=10kb)
            factory.setSizeThreshold(1024 * 1024 * 10);//10兆
            //2.设置临时目录(不建议更改)
            factory.setRepository(new File(""));
            /*******************四.文件大小限制**************************/
            ServletFileUpload fileUpload = new ServletFileUpload(factory);
            //1.单个上传文件大小(单位:字节 默认大小:2097152字节=2兆)
            fileUpload.setFileSizeMax(1024 * 1024 * 10);//10兆
            //2.一次完整请求的所有上传数据+文件大小
            fileUpload.setSizeMax(1024 * 1024 * 20);//20兆

        } catch (Exception ex) {
        }
    }

    /**
     * 保存文件
     *
     * @param req
     */
    private void saveFile(HttpServletRequest req, FileUpUtil fileUpUtil) {
        //1.唯一标识1
        String dateStr = new SimpleDateFormat("yyyyMMddHHmmsssss").format(new Date());
        String dirStr = "/upload/" + dateStr + "";
        // (不可用)获取的是磁盘根目录的绝对路径(D:/img/1234565555)
        // String xDirPath = dir.getAbsolutePath();
        // (可用)获取的是web文件夹下面的绝对路径(D:/img/1234565555)
        String xDirPath = req.getServletContext().getRealPath(dirStr);
        File dir = new File(xDirPath);
        if (!dir.exists()) {
            dir.mkdirs();
        }
        fileUpUtil.saveFormFile(xDirPath, "");
    }
}
package com.jdbc.library.common;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class FileUpUtil {

    private HttpServletRequest _res;
    private DiskFileItemFactory _factory;
    private ServletFileUpload _fileUpload;
    private Map<String, String> _paraMap = new HashMap<String, String>();

    public FileUpUtil(HttpServletRequest res) {
        _res = res;
        _factory = new DiskFileItemFactory();
        _fileUpload = new ServletFileUpload(_factory);
    }

    /**
     * 保存上传文件到本地
     *
     * @param xDirPath  文件绝对路径(不包含文件名)
     * @param xFileName 文件名(图片.JPG)
     */
    public void saveFormFile(String xDirPath, String xFileName) {
        try {
            List<FileItem> fileItemList = _fileUpload.parseRequest(_res);
            for (FileItem fileItem : fileItemList) {
                //是否存储在内存中
                fileItem.isInMemory();
                //找到文件类型参数
                if (!fileItem.isFormField()) {
                    String fileName = xFileName.length() > 0 ? xFileName : fileItem.getName();
                    String absoluRootPath = xDirPath.length() > 0 ? xDirPath : _res.getServletContext().getRealPath(_res.getServletContext().getInitParameter("FileUpPath"));
                    String path = absoluRootPath + "/" + fileName;
                    fileItem.write(new File(path));
                } else {
                    String paraName = fileItem.getFieldName();
                    String paraVal = fileItem.getString();
                    _paraMap.put(paraName, paraVal);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取所有参数名和参数值(除去file类型参数)
     *
     * @return
     */
    public Map<String, String> getFormPara() {
        return _paraMap;
    }


}

下载:

前端页面:


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>file_download</title>
</head>
<body>

<%--GET请求:后台验证--%>
<%--<a href="${pageContext.request.contextPath}/FileDownTest?fileName=测试.jpg">点击下载</a>--%>

<%--POST请求:后台验证--%>
<form action="${pageContext.request.contextPath}/FileDownTest">
    <img src="${pageContext.request.contextPath}/upload/测试.jpg" width="200"
         height="200"/>
    <%--无法保证下载安全--%>
    <%--<a href="${pageContext.request.contextPath}/img/测试.jpg">点击下载</a>--%>
    <input type="hidden" name="fileName" value="测试.jpg"/>
    <input type="submit" value="点击下载" style="width:120px; height: 30px"/>
</form>
</body>
</html>

后台代码:

package com.study.jsp.test;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
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.file.Files;
import java.nio.file.Paths;

@WebServlet("/FileDownTest")
public class FileDownTestServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //GET请求设置Server.xml的Connector
        //POST请求设置
        req.setCharacterEncoding("UTF-8");
        String fileName = req.getParameter("fileName");
        if(fileName==null||"".equals(fileName))
        {
            return;
        }
        //GET请求不需要二次编码,POST请求需要二次编码
        fileName = req.getMethod().toLowerCase().equals("get") ? fileName : new String(fileName.getBytes("ISO-8859-1"), "utf-8");
        //找到资源的位置,读取到内存,响应给浏览器:
        String realPath = super.getServletContext().getRealPath(super.getServletContext().getInitParameter("FileDownPath"));
        String filePath = realPath + "\\" + fileName;
        ServletOutputStream out = resp.getOutputStream();
        //设置响应头
        resp.setContentType("application/x-msdownload");
        //获取请求头信息Use-Agent
        String userAgent = req.getHeader("User-Agent");
        if (userAgent.contains("MSIE")) {
            //IE
            fileName = URLEncoder.encode(fileName, "UTF-8");
        } else {
            //非IE
            fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
        }
        //设置下载的文件名称
        resp.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
        //将数据响应到浏览器
        Files.copy(Paths.get(filePath), out);
    }
}
发布了121 篇原创文章 · 获赞 48 · 访问量 8万+

猜你喜欢

转载自blog.csdn.net/liuchang19950703/article/details/102722672