码迷,mamicode.com
首页 > 其他好文 > 详细

commons-fileupload实现文件按日期进行存储带缓存

时间:2019-09-01 16:29:04      阅读:64      评论:0      收藏:0      [点我收藏+]

标签:print   val   输入   pack   exist   int   parent   common   att   

JSP

 1 <%--
 2   Created by IntelliJ IDEA.
 3   User: Ghh
 4   Date: 2019/9/1
 5   Time: 14:27
 6   To change this template use File | Settings | File Templates.
 7 --%>
 8 <%@ page contentType="text/html;charset=UTF-8" language="java" %>
 9 <html>
10   <head>
11     <title>文件上传</title>
12   </head>
13   <body>
14   <form action="${pageContext.request.contextPath}/uploadServlet" method="post" enctype="multipart/form-data">
15     <input type="file" name="image" id="image"><br>
16     <input type="submit" value="上传">
17   </form>
18   </body>
19 </html>

Servlet

package com.ghh.upload;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
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.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.util.List;
import java.util.UUID;

/**
 * @author Ghh
 * @date 2019/9/1 14:32
 * @Description
 */
@WebServlet(name = "UploadServlet",urlPatterns = {"/uploadServlet"})
public class UploadServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request,response);
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        InputStream is = null;
        FileOutputStream fileOutputStream = null;

        boolean isMultipart = ServletFileUpload.isMultipartContent(request);
        if(!isMultipart){
            throw new RuntimeException("该请求不支持文件上传");
        }
        DiskFileItemFactory itemFactory = new DiskFileItemFactory();
        //设置上传文件大于3M会启动临时文件目录
        itemFactory.setSizeThreshold(1024*1024*3);
        //指定临时文件存储目录
        String tempPath = this.getServletContext().getRealPath("/temp");
        System.out.println("tempPath = " + tempPath);
        File temp = new File(tempPath);
        if(!temp.exists()){
            temp.mkdirs();
        }
        itemFactory.setRepository(temp);
        ServletFileUpload servletFileUpload = new ServletFileUpload(itemFactory);
        try {
            List<FileItem> fileItems = servletFileUpload.parseRequest(request);
            for (FileItem fileItem : fileItems) {
                if(fileItem.isFormField()){
                    //普通字段
                    String fieldName = fileItem.getFieldName();
                    String fileValue = fileItem.getString("UTF-8");
                    System.out.println(fieldName+"===="+fileValue);
                }else{
                    String fileName = fileItem.getName();
                    String suffer = fileName.substring(fileName.lastIndexOf("."));
                    UUID uuid = UUID.randomUUID();
                    fileName = uuid+suffer;
                    System.out.println("fileName = " + fileName);
                    //获取输入流
                    is = fileItem.getInputStream();
                    //创建输出流
                    String path = this.getServletContext().getRealPath("/upload");
                    //根据年月日创建多级目录
                    LocalDate now = LocalDate.now();
                    int year = now.getYear();
                    int month = now.getMonthValue();
                    int day = now.getDayOfMonth();
                    path = path+File.separator+year+File.separator+month+File.separator+day;
                    System.out.println("path = " + path);
                    //创建父目录
                    File parentDir = new File(path);
                    if(!parentDir.exists()){
                        parentDir.mkdirs();
                    }
                    File file = new File(path,fileName);
                    fileOutputStream = new FileOutputStream(file);
                    byte[] bytes = new byte[1024];
                    int len = -1;
                    while ((len = is.read(bytes))!=-1){
                        fileOutputStream.write(bytes,0,len);
                    }
                    fileItem.delete();
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        }finally {
            try {
                is.close();
                fileOutputStream.close();
            }catch (Exception e){
                e.printStackTrace();
            }

        }

    }
}

  

 

commons-fileupload实现文件按日期进行存储带缓存

标签:print   val   输入   pack   exist   int   parent   common   att   

原文地址:https://www.cnblogs.com/gaohuanhuan/p/11442416.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!