1.pom.xml百度
2.核心:
2.1实体类 FileUploadDataBucket:
package com.dzpykj.files; import java.io.File; /** * 上传文件暂存数据的桶 * @author ChaiXY */ public class FileUploadDataBucket { /**即将要保存的文件*/ public File desFile; /**源文件*/ public File srcFile; /**源文件名(带后缀)*/ public String srcFileName; /**储存文件的名称(带后缀)*/ public String desFileName; /**文件类型*/ public String suffixName; /**基础路径*/ public String basePath; /**针对不同功能存放文件可能有不同的文件夹,或者同一模块不同文件类型要存在不同的文件夹,都会在基础路径下新建文件夹,此字段用于存放基础路径后的各自的路径*/ public String ownPath; /**数据存储的存放路径*/ public String dbFilePath; /**文件大小*/ public String fileSize; /**文件md5*/ public String contentMD5; public File getDesFile() { return desFile; } public void setDesFile(File desFile) { this.desFile = desFile; } public File getSrcFile() { return srcFile; } public void setSrcFile(File srcFile) { this.srcFile = srcFile; } public String getSrcFileName() { return srcFileName; } public void setSrcFileName(String srcFileName) { this.srcFileName = srcFileName; } public String getDesFileName() { return desFileName; } public void setDesFileName(String desFileName) { this.desFileName = desFileName; } public String getSuffixName() { return suffixName; } public void setSuffixName(String suffixName) { this.suffixName = suffixName; } public String getBasePath() { return basePath; } public void setBasePath(String basePath) { this.basePath = basePath; } public String getOwnPath() { return ownPath; } public void setOwnPath(String ownPath) { this.ownPath = ownPath; } public String getDbFilePath() { return dbFilePath; } public void setDbFilePath(String dbFilePath) { this.dbFilePath = dbFilePath; } public String getFileSize() { return fileSize; } public void setFileSize(String fileSize) { this.fileSize = fileSize; } public String getContentMD5() { return contentMD5; } public void setContentMD5(String contentMD5) { this.contentMD5 = contentMD5; } }
2.2上传文件工具类FileUploadUtils:
package com.dzpykj.files; import java.io.File; import java.io.IOException; import java.math.BigDecimal; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Random; import javax.servlet.http.HttpServletRequest; import org.apache.commons.codec.digest.DigestUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.web.multipart.MultipartFile; import org.springframework.web.multipart.MultipartHttpServletRequest; import org.springframework.web.multipart.commons.CommonsMultipartResolver; /** * 文件上传 * @author ChaiXY */ public class FileUploadUtils { /** * 上传文件,并且回传数据桶(存储要保存到数据库的数据) * @param request * @param basePath 基础路径(前后不要携带分隔符,工具类会自动补全) * @param ownPath 针对不同功能存放文件可能有不同的文件夹,或者同一模块不同文件类型要存在不同的文件夹,都会在基础路径下新建文件夹,此字段用于存放基础路径后的各自的路径(前后不要携带分隔符,工具类会自动补全) * @return 数据桶 */ public static List<FileUploadDataBucket> uploadFiles(HttpServletRequest request, String basePath, String ownPath) throws IOException { // 创建一个通用的多部分解析器 CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext()); List<FileUploadDataBucket> dataBuckets = new ArrayList<>(); // 判断 request 是否有文件上传,即多部分请求 if (multipartResolver.isMultipart(request)) { // 转换成多部分request MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request; // 取得request中的所有文件名 Iterator<String> iter = multiRequest.getFileNames(); while (iter.hasNext()) { List<MultipartFile> multipartFiles = multiRequest.getFiles(iter.next()); for(MultipartFile multipartFile:multipartFiles){ String srcFileName = multipartFile.getOriginalFilename();// 原名称 带后缀 String suffixName = srcFileName.substring(srcFileName.lastIndexOf(".") + 1);// 文件类型 String contentMD5 = DigestUtils.md5Hex(multipartFile.getBytes()); double size = (multipartFile.getSize() * 1.0) / (1024 * 1.0) / (1024 * 1.0); BigDecimal bg = new BigDecimal(size); double f1 = bg.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue(); String fileSize = f1 + ""; String desFileName = generateFileName() + "." + suffixName; String dbFilePath = ownPath + File.separator + desFileName; String desFilePath = basePath + File.separator + dbFilePath; File desFile = new File(desFilePath); if (!desFile.exists()) { desFile.mkdirs(); } if (StringUtils.isNotBlank(srcFileName)) { multipartFile.transferTo(desFile); FileUploadDataBucket fudb = new FileUploadDataBucket(); fudb.setBasePath(basePath); fudb.setContentMD5(contentMD5); fudb.setDbFilePath(dbFilePath); fudb.setDesFile(desFile); fudb.setDesFileName(desFileName); fudb.setFileSize(fileSize); fudb.setOwnPath(ownPath); fudb.setSrcFileName(srcFileName); fudb.setSuffixName(suffixName); dataBuckets.add(fudb); } } } } return dataBuckets; } private static String generateFileName(){ String dateStr = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()); long timeMillis = System.currentTimeMillis(); int random = new Random().nextInt(90)+10; return dateStr+timeMillis+random; } }
2.3配置文件
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize">
<value>104857600</value>
</property>
<property name="maxInMemorySize">
<value>4096</value>
</property>
<property name="defaultEncoding">
<value>utf-8</value>
</property>
<!-- <property name="defaultEncoding" value="UTF-8" /> -->
</bean>
3.简单的测试
3.1Controller层FileUploadTestController:
package com.dzpykj.files.upload; import java.io.IOException; import java.util.List; import javax.servlet.http.HttpServletRequest; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import com.dzpykj.files.FileUploadDataBucket; import com.dzpykj.files.FileUploadUtils; import com.fasterxml.jackson.databind.ObjectMapper; @Controller public class FileUploadTestController { @RequestMapping("/fileUpload") @ResponseBody public String upload(HttpServletRequest req) throws IOException{ List<FileUploadDataBucket> dataBuckets = FileUploadUtils.uploadFiles(req,"E:\\fiels","pic"); String jsonStr = new ObjectMapper().writeValueAsString(dataBuckets).toString(); System.out.println(jsonStr); return jsonStr; } }
3.2简单jsp页面 fileUpload.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <form action="/fileUpload" method="post" enctype="multipart/form-data"> <input type="file" name="fiel1" /> <br> <input type="file" name="fiel2" /> <br> <input type="submit" value="上传文件" /> </form> </body> </html>