jsp实现简单的文件上传与下载功能

在家闲的发慌,只能通过学习来解解闷,刚好学到jsp(虽然很多人说这个过时了,但学校却要学,拓宽一下知识面,也没什么不好…)。博客中如有哪里不对,还望大佬以留言或邮箱方式指正,邮箱地址 [email protected]

一.文件上传

  1. 前端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="file" name="img">
    <input type="submit" value="上传">
</form>
<a href="/download?filename=2.jpg">下载</a>
</body>
</html>

  1. 后端Servlet 代码,用到了两个jar包(1:commons-fileupload-1.3.1.jar 2:commons-io-2.4.jar)
package com.home.lyp.servlet;

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

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.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;

@WebServlet(name = "UploadServlet",urlPatterns = "/upload")
public class UploadServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp){
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp){
        try {
            req.setCharacterEncoding("utf-8");
            resp.setCharacterEncoding("utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        // 上传
        boolean flag = ServletFileUpload.isMultipartContent(req);
        if (flag){
            DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
            ServletFileUpload servletFileUpload = new ServletFileUpload(fileItemFactory);
            // 设置上传时临时缓冲区大小
            fileItemFactory.setSizeThreshold(1024*2);
            String pathTemp = req.getSession().getServletContext().getRealPath("uploadtemp");
            // 设置上传临时目录
            fileItemFactory.setRepository(new File(pathTemp));
            // 控制上传文件大小
            servletFileUpload.setSizeMax(1024*1024);
            try {
                List<FileItem> items = servletFileUpload.parseRequest(req);
                    for (FileItem item : items) {
                        // 拿网页表单name属性值
                        String name = item.getFieldName();
                        if (name.equals("img")){
                            //item.getString();
                            System.out.println(name);
                            // 拿上传的文件
                            String FileName = item.getName();
                            // 简单的判断拿到的文件的后缀
                            String ext = FileName.substring(FileName.indexOf(".")+1);
                            System.out.println(ext);
                            if(!(ext.equals("png") || ext.equals("jpg") || ext.equals("gif") || ext.equals("jpeg"))){
                                System.out.println("文件类型有误");
                                req.getRequestDispatcher("succes.jsp").forward(req,resp);
                                return;
                            }else {
                                // 上传路径
                                String path = req.getSession().getServletContext().getRealPath("upload");
                                File file = new File(path,FileName);
                                item.write(file);
                            }
                        }
                    }
            } catch (FileUploadBase.SizeLimitExceededException e){
                System.out.println("上传文件超出限制大小");
            }
            catch (FileUploadException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        try {
            req.getRequestDispatcher("succes.jsp").forward(req,resp);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

二,下载

package com.home.lyp.servlet;

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.io.InputStream;
import java.net.URLEncoder;


@WebServlet(name = "DownloadServlet", urlPatterns = "/download")
public class DownloadServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       doGet(req,resp);

    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        String filename =  req.getParameter("filename");
        // 下载文件需要设置消息头
       // System.out.println(filename);
        resp.addHeader("content-Type","application/octet-stream");// 二进制文件
        // 解决ie下载文件名称乱码问题  URLEncoder.encode(filename,"utf-8")
        resp.addHeader("content-Disposition","attachment;filename="+ URLEncoder.encode(filename,"utf-8"));

        // servlet通过文件地址 将文件转化为输入流 读到servlet中
        InputStream inputStream = getServletContext().getResourceAsStream("/res/"+filename);
        //System.out.println(inputStream);
        // 输出给用户
        ServletOutputStream outputStream = resp.getOutputStream();
        // 缓冲
        byte[] bs = new byte[1024];
        int len ;
      
        while ((len = inputStream.read(bs))!=-1){
            outputStream.write(bs,0,len);
        }
        inputStream.close();
        outputStream.close();
    }
}

你可能感兴趣的:(jsp实现简单的文件上传与下载功能)