Spring MVC文件上传下载工具类
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID; import javax.servlet.http.HttpServletRequest; import org.apache.commons.io.FileUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver; /**
* @Description 操作文件工具类
* @author LJ
* @Date 2016年6月8日 上午11:42:44
* @Version v1.0
*/
public final class OperationFileUtil {
private static final String ENCODING = "utf-8"; /**
* 文件下载
*
* @param filePath
* 文件路径
* @return
* @throws UnsupportedEncodingException
* @throws IOException
*/
public static ResponseEntity<byte[]> download(String filePath) throws UnsupportedEncodingException, IOException {
String fileName = FilenameUtils.getName(filePath);
return downloadAssist(filePath, fileName);
} /**
* 文件下载
*
* @param filePath
* 文件路径
* @param fileName
* 文件名
* @return
* @throws UnsupportedEncodingException
* @throws IOException
*/
public static ResponseEntity<byte[]> download(String filePath, String fileName) throws UnsupportedEncodingException, IOException {
return downloadAssist(filePath, fileName);
} /**
* 文件下载辅助
*
* @param filePath
* 文件路径
* @param fileName
* 文件名
* @return
* @throws UnsupportedEncodingException
* @throws IOException
*/
private static ResponseEntity<byte[]> downloadAssist(String filePath, String fileName) throws UnsupportedEncodingException, IOException {
File file = new File(filePath);
if (!file.isFile() || !file.exists()) {
throw new IllegalArgumentException("filePath 参数必须是真实存在的文件路径:" + filePath);
}
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.setContentDispositionFormData("attachment", URLEncoder.encode(fileName, ENCODING));
return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);
} /**
* 多文件上传
*
* @param request
* 当前上传的请求
* @param basePath
* 保存文件的路径
* @throws IOException
* @throws IllegalStateException
* @return Map<String, String> 返回上传文件的保存路径 以文件名做map的key;文件保存路径作为map的value
*/
public static Map<String, String> multiFileUpload(HttpServletRequest request, String basePath) throws IllegalStateException, IOException {
if (!(new File(basePath).isDirectory())) {
throw new IllegalArgumentException("basePath 参数必须是文件夹路径");
}
return multifileUploadAssist(request, basePath, null);
} /**
* 多文件上传
*
* @param request
* 当前上传的请求
* @param basePath
* 保存文件的路径
* @param exclude
* 排除文件名字符串,以逗号分隔的,默认无可传null
* @return
* @throws IllegalStateException
* @throws IOException
*/
public static Map<String, String> multiFileUpload(HttpServletRequest request, String basePath, String exclude) throws IllegalStateException, IOException {
if (!(new File(basePath).isDirectory())) {
throw new IllegalArgumentException("basePath 参数必须是文件夹路径");
} return multifileUploadAssist(request, basePath, exclude);
} /**
* 多文件上传辅助
*
* @param request
* 当前上传的请求
* @param basePath
* 保存文件的路径
* @param exclude
* 排除文件名字符串,以逗号分隔的,默认无可传null
* @return
* @throws IOException
*/
private static Map<String, String> multifileUploadAssist(HttpServletRequest request, String basePath, String exclude) throws IOException {
exclude = exclude == null ? "" : exclude; Map<String, String> filePaths = new HashMap<String, String>();
File file = null;
// 创建一个通用的多部分解析器
CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
// 判断 request 是否有文件上传,即多部分请求
if (multipartResolver.isMultipart(request)) {
// 转换成多部分request
MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
// get the parameter names of the MULTIPART files contained in this request
Iterator<String> iter = multiRequest.getFileNames();
while (iter.hasNext()) {
// 取得上传文件
List<MultipartFile> multipartFiles = multiRequest.getFiles(iter.next());
for (MultipartFile multipartFile : multipartFiles) {
String fileName = multipartFile.getOriginalFilename();
if (StringUtils.isNotEmpty(fileName) && (!exclude.contains(fileName))) {
file = new File(basePath + changeFilename2UUID(fileName));
filePaths.put(fileName, file.getPath());
multipartFile.transferTo(file);
}
}
}
}
return filePaths;
} /**
* 将文件名转变为UUID命名的 ,保留文件后缀
*
* @param filename
* @return
*/
public static String changeFilename2UUID(String filename) {
String uuid = UUID.randomUUID().toString();
return uuid + "." + FilenameUtils.getExtension(filename);
} /**
* 删除文件
*
* @param filePath
*/
public static void deleteFile(String filePath) {
try {
File file = new File(filePath);
if (file.exists() && file.isFile()) {
file.delete();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Spring MVC文件上传下载工具类的更多相关文章
- Spring MVC文件上传下载(转载)
原文地址: http://www.cnblogs.com/WJ-163/p/6269409.html 上传参考 http://www.cnblogs.com/lonecloud/p/5990060.h ...
- Spring MVC 文件上传下载
本文基于Spring MVC 注解,让Spring跑起来. (1) 导入jar包:ant.jar.commons-fileupload.jar.connom-io.jar. (2) 在src/cont ...
- SFTP 文件上传下载工具类
SFTPUtils.java import com.jcraft.jsch.*; import com.jcraft.jsch.ChannelSftp.LsEntry; import lombok.e ...
- Spring MVC 笔记 —— Spring MVC 文件上传
文件上传 配置MultipartResolver <bean id="multipartResolver" class="org.springframework.w ...
- ftp上传下载工具类
package com.taotao.utils; import java.io.File; import java.io.FileInputStream; import java.io.FileNo ...
- 【Java Web开发学习】Spring MVC文件上传
[Java Web开发学习]Spring MVC文件上传 转载:https://www.cnblogs.com/yangchongxing/p/9290489.html 文件上传有两种实现方式,都比较 ...
- Spring MVC文件上传教程 commons-io/commons-uploadfile
Spring MVC文件上传教程 commons-io/commons-uploadfile 用到的依赖jar包: commons-fileupload 1.3.1 commons-io 2.4 基于 ...
- Spring mvc文件上传实现
Spring mvc文件上传实现 jsp页面客户端表单编写 三个要素: 1.表单项type="file" 2.表单的提交方式:post 3.表单的enctype属性是多部分表单形式 ...
- Spring MVC 文件上传 & 文件下载
索引: 开源Spring解决方案--lm.solution 参看代码 GitHub: pom.xml WebConfig.java index.jsp upload.jsp FileUploadCon ...
随机推荐
- vs 已经加入了引用,编译还是提示没有加入引用
已经加入了引用,可是.编译还是通只是. 原因:项目总体框架是.Net FramWork4.5,nep中的框架也是4.5.而编译只是的project是4.0. 解决的方法:将编译只是的项目框架改为4.5
- UITextField placeholder text color
iOS6 and Later 改变UITextField 中占位符 提示文本的文字颜色 在新版本中(iOS6以后)iOS提供一种 Key = value 属性的方式,来改变UI的属性内容.以UITex ...
- SQLServer待优化语句查询
SELECT top 100 (total_elapsed_time / execution_count)/1000 N'平均时间ms' ,total_elapsed_time/1000 N'总花费时 ...
- DCDC电路电感和电容啸叫的原因
电感啸叫原因 如果耳朵能听到啸叫(吱吱声),可以肯定电感两端存在一个20HZ-20KHZ(人耳范围)左右的开关电流. 例如DC-DC电路的电感啸叫,由于负载电流过大 DC内部有一个限流保护电路,当负载 ...
- Lua学习四----------Lua变量
© 版权声明:本文为博主原创文章,转载请注明出处 1.Lua变量 - 变量在使用前,必须在代码中进行声明,即创建该变量 - 编译程序执行代码之前编译器需要知道如何给语句变量开辟存储区,用于存储变量的值 ...
- WPF converter(包含传递复杂参数)
单值转换器 将单一值转换为特定类型的值,以日期转换为例如下: 1.定制DateConverter类,其中当值从绑定源传播给绑定目标时,调用方法Convert. 1 public class DateC ...
- 漫反射和Lambert模型
粗糙的物体表面向各个方向等强度地反射光,这种等同地向各个方向散射的现象称为光的漫反射(diffuse reflection).产生光的漫反射现象的物体表面称为理想漫反射体,也称为朗伯(Lambert) ...
- c# 根据枚举Value 获得名称
// 定义枚举类型enum sotype : int { book=1, pen=2, other=3 } // 输出名称 switch (Enum.GetName(typeof(sotype), 1 ...
- 2017-01-20_dp测试
题目:http://files.cnblogs.com/files/shenben/2017-01-20problems.pdf 数据包(含解题报告):http://files.cnblogs.com ...
- python知识点导图(搜集)
第一章 基本环境 第二章 内置类型 第三章 表达式 第四章 函数 第五章 迭代器 第六章 模块 第七章 类 第八章 异常 第九章 装饰器 第十章 描述符 第十一章 元类 第十二章 标准库 Re模块 附 ...