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. 学习使用用Eclipse编写java程序

    本文讲解了在Eclipse中完成一个HelloWorld程序的编写过程. 刚刚学习java的同学们可能用 记事本编写java源代码,在命令提示符中完成java程序的编译和运行过程.这样的方法对于学习j ...

  2. 一种把dll放在不同目录的巧妙方法

    想必C#的开发者都遇到过这个问题,引用的dll都放在根目录下,随着项目的日益增大,根目录下充满了各种各样的dll,非常的不美观. 如果能够把dll按照想要的目录来存放,那么系统就美观多了,以下是我常用 ...

  3. 16:Merge

    题目描述 数据表记录包含表索引和数值,请对表索引相同的记录进行合并,即将相同索引的数值进行求和运算,输出按照key值升序进行输出. 输入描述:先输入键值对的个数,然后输入成对的index和value值 ...

  4. hashCode与equals的作用与区别及应当注意的细节

    最近去面试了几家公司,被问到hashCode的作用,虽然回答出来了,但是自己还是对hashCode和equals的作用一知半解的,所以决定把它们研究一下. 以前写程序一直没有注意hashCode的作用 ...

  5. leetCode 84.Largest Rectangle in Histogram (最大矩形直方图) 解题思路和方法

    Given n non-negative integers representing the histogram's bar height where the width of each bar is ...

  6. PHP和mysql的长连接

    关于 PHP MySQL 长连接.连接池的一些探索 PHP连接MySQL的方式,用的多的是mysql扩展.mysqli扩展.pdo_mysql扩展,是官方提供的.php的运行机制是页面执行完会释放所有 ...

  7. 【WPF学习笔记】之如何通过后台C#代码添加(增/删/改按钮)实现对SQLServer数据库数据的更改

    首先,需要连接SQLServer数据库的服务器名称server.数据库名database.数据库用户名uid以及密码pwd,如下图: 然后需要以下数据库SQL代码段,还有一个myHelper.cs代码 ...

  8. Java 获取本地IP地址

    private static String getIpAddress( ){ String ip = ""; Collection<InetAddress> colIn ...

  9. 03 redis之string类型命令解析

    Redis字符串类型的操作 set key value [ex 秒数] / [px 毫秒数] [nx] /[xx] 如: set a 1 ex 10 , 10秒有效 Set a 1 px 9000 , ...

  10. ASP.NET动态网站制作(10)-- JQ(2)

    前言:jq的第二节课. 内容: 1.管理选择结果:  (1)获取元素个数:$("img").size():获取页面中所有“img”个数:  (2)提取元素:$("img[ ...