java文件上传(FileItem接收)

java文件上传服务类及接口编写

本文例子中已整合springMvc,如使用本例的controller请自行整合,或参考github代码https://github.com/MrJcL/Demo.git 中的webappdemo

注意:springMvc的配置文件中用到MultipartResolver会导致upload.parseRequest(request);返回为空

主要依赖的maven

<!-- file -->
 <dependency>
     <groupId>commons-fileupload</groupId>
     <artifactId>commons-fileupload</artifactId>
     <version>1.3.3</version>
 </dependency>
 <dependency>
     <groupId>org.apache.commons</groupId>
     <artifactId>commons-io</artifactId>
     <version>1.3.2</version>
 </dependency>
FileForm
package com.common.form;

/**
 * @program: 文件上传表单类
 * @Date: 2019/2/27 21:26
 * @Author: LiJc
 * @Description:
 */
public class FileForm {

	private String fileId;
	private String name;
	private String filePath;
	private String contentType;
	private Long size;
	private String fileUrl;
	
	public String getFileId() {
		return fileId;
	}
	public void setFileId(String fileId) {
		this.fileId = fileId;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getFilePath() {
		return filePath;
	}
	public void setFilePath(String filePath) {
		this.filePath = filePath;
	}
	public String getContentType() {
		return contentType;
	}
	public void setContentType(String contentType) {
		this.contentType = contentType;
	}
	public Long getSize() {
		return size;
	}
	public void setSize(Long size) {
		this.size = size;
	}
	public String getFileUrl() {
		return fileUrl;
	}
	public void setFileUrl(String filePath) {
		this.fileUrl = filePath;
	}
}

uploadService
package com.common.service;

import com.common.form.FileForm;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.MessageFormat;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @program: Demo
 * @Date: 2019/2/22 12:24
 * @Author: LiJc
 * @Description:
 *      springMvc配置的MultipartResolver处理器已经对文件做了解析(List<FileItem> items = upload.parseRequest(request);)
 *      如需要使用MultipartResolver配置,可使用MultipartFile file[]接收
 */
@Service
public class UploadService {
    /** 上传文件根路径 */
    private String uploadRootPath;

    /** 上传文件子路径 */
    private String subPath = "";

    /** 上传文件是否重命名 */
    private boolean isRename = true;

    public String getUploadRootPath() {
        if(StringUtils.isEmpty(this.uploadRootPath)){
            this.uploadRootPath = "D:\\upload";
        }
        return uploadRootPath;
    }

    public void setUploadRootPath(String uploadRootPath) {
        this.uploadRootPath = uploadRootPath;
    }

    public String getSubPath() {
        return subPath;
    }

    public void setSubPath(String subPath) {
        this.subPath = subPath;
    }

    public boolean isRename() {
        return isRename;
    }

    public void setRename(boolean isRename) {
        this.isRename = isRename;
    }

    /**
     * 上传文件
     * @param request
     * @return
     * @throws Exception
     */
    public List<FileForm> uploadFiles(HttpServletRequest request) throws Exception {

        List<FileForm> list = new ArrayList<FileForm>();

        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);

        List<FileItem> items = upload.parseRequest(request);
        Iterator<FileItem> itr = items.iterator();
        int i = 0;
        while (itr.hasNext()) {
            FileItem item = (FileItem) itr.next();
            if (!item.isFormField() && item.getName() != null && !item.getName().equals("")) {
                // 上传文件
                FileForm fileForm = this.uploadFile(item);
                fileForm.setFileId(UUID.randomUUID().toString());
                list.add(fileForm);
                i++;

                // TODO 写入数据库
            }
        }

        return list;
    }

    /**
     * 上传文件
     * @param item
     * @return
     * @throws Exception
     */
    public FileForm uploadFile(FileItem item) throws Exception {
        // item.getName()返回上传文件在客户端的完整路径名称
        File tempFile = new File(item.getName());
        String fileName = tempFile.getName();// 原始文件名
        String filePath = this.getSavePath(this.subPath, fileName, this.isRename);

        // 上传文件
        File file = new File(this.getUploadRootPath() + filePath);
        FileUtils.forceMkdir(file.getParentFile());
        item.write(file);

        FileForm fileForm = new FileForm();
        fileForm.setName(fileName);
        fileForm.setFilePath(filePath);// 存放路径
        fileForm.setContentType(item.getContentType());// 数据格式
        fileForm.setSize(item.getSize());// 文件大小
        fileForm.setFileUrl(filePath);

        return fileForm;
    }

    /**
     * 构建文件路径
     * @param subPath
     * @param fileName
     * @param isRename
     * @return
     */
    public String getSavePath(String subPath, String fileName, boolean isRename) {
        // 处理子路径
        if (!StringUtils.isBlank(subPath)) {
            subPath += "\\";
        } else {
            subPath = "";
        }
        // 处理日期路径
        Date date = new Date();
        SimpleDateFormat yyyy = new SimpleDateFormat("yyyy");
        SimpleDateFormat mm = new SimpleDateFormat("MM");
        String datePath = MessageFormat.format("{0}\\{1}\\", yyyy.format(date), mm.format(date));
        if(isRename){
            int dotIndex = fileName.lastIndexOf(".");
            String ext = fileName.substring(dotIndex, fileName.length());
            fileName = UUID.randomUUID().toString() + ext;
        }
        return "\\" + subPath + datePath + fileName;
    }
}

UploadController
package com.common.controller;

import com.common.form.FileForm;
import com.common.service.UploadService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.inject.Inject;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @program: Demo
 * @Date: 2019/2/25 16:04
 * @Author: LiJc
 * @Description:
 */
@Controller
@RequestMapping("upload")
public class UploadController {

    @Inject
    private UploadService uploadService;

    @PostMapping("exec")
    @ResponseBody
    public String exec(HttpServletRequest request){
        System.out.println("exec");
        try{
            List<FileForm> fileForms = this.uploadService.uploadFiles(request);
        }catch (Exception e){
            e.printStackTrace();
            return "error";
        }
        return "success";
    }

}

upload.jsp(简版)
<%@ page contentType="text/html;charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-type" content="text/html; charset=UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/>
    <title>多文件上传</title>
</head>
<body>
<form method="post" action="/webappdemo/upload/exec" enctype="multipart/form-data">
    <input type="file" name="file"><br>
    <input type="file" name="file"><br>
    <input type="file" name="file"><br>
    <input type="submit" value="提交">
</form>
</body>
</html>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值