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文件上传下载工具类的更多相关文章

  1. Spring MVC文件上传下载(转载)

    原文地址: http://www.cnblogs.com/WJ-163/p/6269409.html 上传参考 http://www.cnblogs.com/lonecloud/p/5990060.h ...

  2. Spring MVC 文件上传下载

    本文基于Spring MVC 注解,让Spring跑起来. (1) 导入jar包:ant.jar.commons-fileupload.jar.connom-io.jar. (2) 在src/cont ...

  3. SFTP 文件上传下载工具类

    SFTPUtils.java import com.jcraft.jsch.*; import com.jcraft.jsch.ChannelSftp.LsEntry; import lombok.e ...

  4. Spring MVC 笔记 —— Spring MVC 文件上传

    文件上传 配置MultipartResolver <bean id="multipartResolver" class="org.springframework.w ...

  5. ftp上传下载工具类

    package com.taotao.utils; import java.io.File; import java.io.FileInputStream; import java.io.FileNo ...

  6. 【Java Web开发学习】Spring MVC文件上传

    [Java Web开发学习]Spring MVC文件上传 转载:https://www.cnblogs.com/yangchongxing/p/9290489.html 文件上传有两种实现方式,都比较 ...

  7. Spring MVC文件上传教程 commons-io/commons-uploadfile

    Spring MVC文件上传教程 commons-io/commons-uploadfile 用到的依赖jar包: commons-fileupload 1.3.1 commons-io 2.4 基于 ...

  8. Spring mvc文件上传实现

    Spring mvc文件上传实现 jsp页面客户端表单编写 三个要素: 1.表单项type="file" 2.表单的提交方式:post 3.表单的enctype属性是多部分表单形式 ...

  9. Spring MVC 文件上传 & 文件下载

    索引: 开源Spring解决方案--lm.solution 参看代码 GitHub: pom.xml WebConfig.java index.jsp upload.jsp FileUploadCon ...

随机推荐

  1. 开发SharePoint 自定义WebService 的小工具

    是一个开源的项目,地址:http://www.codeproject.com/Articles/10728/WSS-Web-Service-DISCO-and-WSDL-Generator-Helpe ...

  2. 可以添加自定义的Select控件

    1.控件dom <select name="WebSiteTarget" id="WebSiteTarget" class="w1" ...

  3. c++实现二叉搜索树

    自己实现了一下二叉搜索树的数据结构.记录一下: #include <iostream> using namespace std; struct TreeNode{ int val; Tre ...

  4. 彻底解决zend studio 下 assignment in condition警告

    最近在mac系统下安装zend studio作为php开发工具,把以前的代码导入,发现项目中有很多 “assignment in condition”的警告,造成原因是在条件判断的if.while中使 ...

  5. IDEA小技巧-随时更新

    © 版权声明:本文为博主原创文章,转载请注明出处 1.设置删除一行快捷键 File->Settings->keymap->Delete Line 2.设置代码提示快捷键 File-& ...

  6. NHibernate3剖析:Mapping篇之ConfORM实战(1):概览

    ORuM思想浮出 对于ORM(Object Relational Mapping)我们太熟悉了,可是我们从还有一个角度能够想象出ORuM(Object Relational un-Mapping)的思 ...

  7. leetCode 95.Unique Binary Search Trees II (唯一二叉搜索树) 解题思路和方法

    Given n, generate all structurally unique BST's (binary search trees) that store values 1...n. For e ...

  8. Asp.Net北大青鸟总结(四)-使用GridView实现真假分页

    这段时间看完了asp.net视频.可是感觉到自己的学习好像没有巩固好,于是又在图书馆里借了几本关于asp.net的书感觉真的非常好自己大概对于asp.net可以实现主要的小Demo.可是我知道仅仅有真 ...

  9. 知识复习(LDT+TSS+GATE+INTERRUPT)

    [1]README 1.0)由于实现进程的切换任务,其功能涉及到 LDT + TSS +GATE + INTERRUPT:下面我们对这些内容进行复习: 1.1) source code from or ...

  10. WPF之DataTemplateSelector技巧

    WPF中如何通过一个属性来控制对象的模板,属性值改变时对象的模板会跟随改变? 两个关键点   1 属性/对象更改通知 方法一:继承INotifyPropertyChanged接口,当属性值更改时需要让 ...