A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© yellowstar 初级黑马   /  2019-9-19 15:56  /  797 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

文件上传需要使用阿帕奇基金会提供的
commons-fileupload-1.3.1.jar
commons-io-2.4.jar
两个jar包
servlet代码
------------------------------------------
[Java] 纯文本查看 复制代码
package com.yellow.web.servlet;

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.ServletContext;
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.time.LocalDate;
import java.util.List;
import java.util.UUID;

@WebServlet("/upload")
public class UploadServlet extends HttpServlet {

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

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        boolean multipartContent = ServletFileUpload.isMultipartContent(req);
        if(multipartContent){
            DiskFileItemFactory factory = new DiskFileItemFactory();

            //设置临时文件的路径,以及开启临时文件的大小
            //1MB就开启
            factory.setSizeThreshold(1024*1024);
            //获取临时文件路径
            String temp = req.getServletContext().getRealPath("/temp");
            System.out.println("temp = " + temp);
            File temppath = new File(temp);
            if(!temppath.exists()){
                //如果不存在创建
                temppath.mkdirs();
            }
            factory.setRepository(temppath);
            ServletFileUpload sfu = new ServletFileUpload(factory);

            try {
                List<FileItem> items = sfu.parseRequest(req);
                for (FileItem item : items) {
                    if(!item.isFormField()){
                        //说明讲就是文件上传
                        //获取文件名
                        String fileName = item.getName();
                        //截取非法文件名称
                        fileName=fileName.substring(fileName.lastIndexOf("\\")+1);
                        //使用UUID加密,方式文件名称重复
                        fileName=UUID.randomUUID()+"_"+ fileName;
                        //设置文件以日期子目录来存储
                        LocalDate ld =  LocalDate.now();
                        //获取年月日
                        int year = ld.getYear();
                        int month = ld.getMonthValue();
                        int day = ld.getDayOfMonth();
                        //设置文件的上传名称
                        String upload=req.getServletContext().getRealPath("/upload");
                        upload=upload+"/"+year+"/"+month+"/"+day;
                        System.out.println("upload = " + upload);
                        File uploadpath = new File(upload);
                        if(!uploadpath.exists()){
                            //创建
                            uploadpath.mkdirs();
                        }
                        File uploadFile = new File(uploadpath,fileName);
                        System.out.println("uploadFile = " + uploadFile.getAbsolutePath());
                        if(!uploadFile.exists()){
                            uploadFile.createNewFile();
                        }

                        item.write(uploadFile);
                    }
                    //设置手动删除临时文件
                    item.delete();

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

jsp代码
-------------------
[mw_shl_code=html,true]<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/upload" enctype="multipart/form-data" method="post">
    <input type="file" name="photo"><br>
    <input type="submit" value="上传">
</form>
</body>
</html>



    }
}
[/mw_shl_code]servlet代码
----------------------

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马