java spring文件下载_SpringMVC实现文件上传和下载的工具类

本文主要目的是记录自己基于SpringMVC实现的文件上传和下载的工具类的编写,代码经过测试可以直接运行在以后的项目中。

开发的主要思路是对上传和下载文件进行抽象,把上传和下载的核心功能抽取出来分装成类。

我的工具类具体代码如下:

package com.baosight.utils;

import java.io.BufferedInputStream;

import java.io.File;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.util.ArrayList;

import java.util.Arrays;

import java.util.Iterator;

import java.util.List;

import java.util.Properties;

import org.apache.commons.fileupload.util.Streams;

import org.apache.commons.io.FileUtils;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

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;

/**

* springMVC中文件的工具类

*

* @author chenpeng

*

*/

public class MyfileUtils {

private static final Logger logger = LoggerFactory.getLogger(MyfileUtils.class);

/**

* 存储的路径,默认的为c盘符

*/

public static String directory = "c:/";

/**

* 图片的大小配置,默认为2048000

*/

public static long imagesize = 2048000;

/**

* 图片的类型配置默认如下

*/

public static String imagetype = "image/bmp,image/png,image/jpeg,image/jpg";

/**

* 文件上传的大小限制

*/

public static long filesize = 20971520;

/**

* 文件上传文件的类型

*/

public static String filetype = "application/msword,application/pdf,application/zip,video/mpeg,video/quicktime,video/x-sgi-movie,video/mpeg,video/x-msvideo,audio/x-mpeg,application/octet-stream";

/**

* 配置路径的字段

*/

public static final String DIRECTORY = "myfileutils.uploadFileDirectory";

/**

* 配置图片大小的字段

*/

public static final String IMAGESIZE = "myfileutils.imgSize";

/**

* 配置图片类型的字段

*/

public static final String IMAGETYPE = "myfileutils.imgType";

/**

* 文件的大小

*/

public static final String FILESIZE = "myfileutils.fileSize";

/**

* 文件的类型

*/

public static final String FILETYPE = "myfileutils.fileType";

/**

* 文件所支持的全部类型(图片,office文件,压缩包,视频,音频)

*/

public static String[] sporting_filetype;

/**

* 上传的结果

*

* @author cp UPLOAD_SUCCESS:"上传成功" UPLOAD_SIZE_ERROR:"上传文件过大"

* UPLOAD_TYPE_ERROR:"上传文件类型错误" UPLOAD_FILE:"上传文件失败"

*

*/

public static enum Upload {

UPLOAD_SUCCESS("上传成功", 1), UPLOAD_SIZE_ERROR("上传文件过大", 2), UPLOAD_TYPE_ERROR("上传文件类型错误",

3), UPLOAD_FILE("上传文件失败", 4),FILE_DOWNLOAD_SUCCESS("文件下载成功",5),FILE_NOTFOUND("未找到该文件",6);

// 成员变量

private String name;

@SuppressWarnings("unused")

private int index;

// 构造方法

private Upload(String name, int index) {

this.name = name;

this.index = index;

}

// 覆盖toString方法

@Override

public String toString() {

return this.name;

}

}

/**

* static语句块读取配置文件

*/

static {

Properties properties = new Properties();

try {

InputStream in = new BufferedInputStream(MyfileUtils.class.getResourceAsStream("/user-setting.properties"));

properties.load(in);

Iterator it = properties.stringPropertyNames().iterator();

while (it.hasNext()) {

String key = it.next();

String value = properties.getProperty(key);

logger.info("读取配置文件..." + key + ":" + value);

switch (key) {

// 如果是路径

case DIRECTORY:

// 判断是否存在该文件夹如果没有则要重新创建

File file = new File(value);

if (!file.exists() && !file.isDirectory()) {

// 创建文件夹

file.mkdirs();

}

directory = value;

break;

// 如果是图片的格式

case IMAGETYPE:

imagetype = value;

break;

// 如果是图片的大小

case IMAGESIZE:

imagesize = Long.parseLong(value);

break;

// 如果是文件的大小

case FILESIZE:

filesize = Long.parseLong(value);

break;

// 如果是文件的类型

case FILETYPE:

filetype = value;

break;

default:

break;

}

}

// 读取配置后把支持图片的和支持文件的放在一起

String[] imagetypes = imagetype.split(",");

String[] filetypees = filetype.split(",");

sporting_filetype = new String[imagetypes.length+filetypees.length];

System.arraycopy(imagetypes, 0, sporting_filetype, 0, imagetypes.length);

System.arraycopy(filetypees, 0, sporting_filetype, imagetypes.length, filetypees.length);

} catch (FileNotFoundException e) {

logger.error("未发现配置文件");

} catch (IOException e) {

logger.error("读取配置文件失败");

}

}

/**

* 上传文件

*

* @param multipartFiles

* 上传的文件

* @param parentDir

* 上传文件制定的父文件夹,格式为A/b,可以为空

* @param storageFileName

* 上传的文件的别名,注意上传文件名不用带后缀

* @return

*/

public static List uploadFile(MultipartFile[] multipartFiles, String parentDir, String storageFileName) {

List myStrings = new ArrayList<>();

if (multipartFiles != null && multipartFiles.length > 0) {

String laString = "";

String storagePath = "";

// 先判断要存储的文件夹是否存在,如果不存在就重新创建

String path = directory + ((parentDir!=null)?("/" + parentDir):"");

File fileDir = new File(path);

if (!fileDir.exists() && !fileDir.isDirectory()) {

fileDir.mkdirs();

}

for (MultipartFile file : multipartFiles) {

// 先判断文件的类型是否符合配置要求

if (MyfileUtils.checkFileType(file, sporting_filetype)) {

/***** 判断文件的大小 *****/

String type = file.getContentType().substring(0, file.getContentType().lastIndexOf("/"));

// 如果是图片,且大小超过范围的,如果是文件,且大小超过范围的直接返回

if ((type.equals("image") && !MyfileUtils.checkFileSize(file, MyfileUtils.imagesize))

|| (!type.equals("image") && !MyfileUtils.checkFileSize(file, filesize))) {

logger.info("文件过大");

}

// 获取变量名file,文件类型,文件名

logger.info(

"上传的文件:" + file.getName() + "," + file.getContentType() + "," + file.getOriginalFilename());

laString = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));

try {

if (!file.isEmpty()) {

// 判断sotrageName是否为空,如果不为空就以存储的命名,为空就以原来的名称命名

storagePath = path + "/" + ((storageFileName != null) ? (storageFileName + laString)

: file.getOriginalFilename());

logger.info("保存的路径为:" + storagePath);

Streams.copy(file.getInputStream(), new FileOutputStream(storagePath), true);

myStrings.add(storagePath);

}

} catch (Exception e) {

logger.error("上传文件失败");

e.printStackTrace();

}

} else {

logger.info("上传文件类型有误");

}

}

logger.info("上传文件成功");

} else {

logger.info("上传文件失 败");

}

return myStrings;

}

/**

* 下载文件

*

* @param filePath

* 文件的路径

* @param fileReName

* 文件的下载显示的别名

* @return 文件的对象

* @throws IOException

*/

public static ResponseEntity downloadFile(String filePath, String fileReName) throws IOException {

// 指定文件,必须是绝对路径

File file = new File(filePath);

// 下载浏览器响应的那个文件名

String dfileName = new String(fileReName.getBytes("GBK"), "iso-8859-1");

// 下面开始设置HttpHeaders,使得浏览器响应下载

HttpHeaders headers = new HttpHeaders();

// 设置响应方式

headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);

// 设置响应文件

headers.setContentDispositionFormData("attachment", dfileName);

// 把文件以二进制形式写回

ResponseEntity result = null;

try {

result = new ResponseEntity(FileUtils.readFileToByteArray(file), headers, HttpStatus.CREATED);

} catch (Exception e) {

logger.error(e.toString());

}

return result;

}

/**

* 检查文件的格式

*

* @return

*/

public static boolean checkFileType(MultipartFile file, String[] supprtedTypes) {

String fileType = file.getContentType();

logger.info("文件的格式为:"+fileType);

return Arrays.asList(supprtedTypes).contains(fileType);

}

/**

* 判断文件的大小是否符合要求

*

* @param maxSize

* 最大文件

* @return

*/

public static boolean checkFileSize(MultipartFile file, long maxSize) {

logger.info("文件的大小比较:"+file.getSize()+",max:"+maxSize);

return file.getSize() <= maxSize;

}

}

需要注意的是我的工具类使用了如下的配置,对自己的业务需求进行可配置,提高代码的应用场景(user-setting.properties):

# 上传文件的父目录

# 示例:myfileutils.uploadFileDirectory= e:/emp

myfileutils.uploadFileDirectory= D:/MyFILES

# 上传图片的大小

# 示例: myfileutils.imgSize= 2097152

myfileutils.imgSize= 2097152

# 上传图片的格式

# 示例:myfileutils.imgType= image/bmp,image/png,image/jpeg,image/jpg,image/x-png,image/pjpeg

myfileutils.imgType= image/bmp,image/png,image/jpeg,image/jpg,image/x-png,image/pjpeg

# 上传文件的大小(除了图片)

# 示例:myfileutils.fileSize= 20971520

myfileutils.fileSize= 20971520

# 上传文件的类型(除了图片)

# 示例:myfileutils.fileType= application/msword,application/pdf,application/zip,video/mpeg,video/quicktime,video/x-sgi-movie,video/mpeg,video/x-msvideo,audio/x-mpeg,application/octet-stream

myfileutils.fileType= video/avi,application/vnd.ms-powerpoint,application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.wordprocessingml.document,application/msword,application/pdf,application/zip,video/mpeg,video/quicktime,video/x-sgi-movie,video/mpeg,video/x-msvideo,audio/x-mpeg,application/octet-stream

另外本工具类中为了方便调试错误与log4j进行了集成,所以还需要如下的配置文件:

#定义LOG输出级别

log4j.rootLogger=INFO,Console,File

#定义日志输出目的地为控制台

log4j.appender.Console=org.apache.log4j.ConsoleAppender

log4j.appender.Console.Target=System.out

#可以灵活地指定日志输出格式,下面一行是指定具体的格式

log4j.appender.Console.layout = org.apache.log4j.PatternLayout

log4j.appender.Console.layout.ConversionPattern=[%c] - %m%n

#文件大小到达指定尺寸的时候产生一个新的文件

log4j.appender.File = org.apache.log4j.RollingFileAppender

#指定输出目录

log4j.appender.File.File = logs/ssm.log

#定义文件最大大小

log4j.appender.File.MaxFileSize = 10MB

# 输出所以日志,如果换成DEBUG表示输出DEBUG以上级别日志

log4j.appender.File.Threshold = ALL

log4j.appender.File.layout = org.apache.log4j.PatternLayout

log4j.appender.File.layout.ConversionPattern =[%p] [%d{yyyy-MM-dd HH\:mm\:ss}][%c]%m%n

log4j.logger.com.ibatis=DEBUG

log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=DEBUG

log4j.logger.com.ibatis.common.jdbc.ScriptRunner=DEBUG

log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate=DEBUG

log4j.logger.java.sql.Connection=DEBUG

log4j.logger.java.sql.Statement=DEBUG

log4j.logger.java.sql.PreparedStatement=DEBUG

下面就开始来重新创建一个maven的web项目来测试使用下我的工具类:

1.我使用的开发工具为idea,新建一个maven web的项目,然后打开pom.xml配置文件。首先来搭建一下springMVC的开发环境,需要引用相关的jar包,maven的配置文件如下:

02791daf3646bb246edea08621b82816.png

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

4.0.0

com.baosight

testfile

1.0-SNAPSHOT

war

testfile Maven Webapp

http://www.example.com

UTF-8

1.7

1.7

4.0.5.RELEASE

1.7.7

1.2.17

junit

junit

4.11

test

org.springframework

spring-core

${spring.version}

org.springframework

spring-web

${spring.version}

org.springframework

spring-oxm

${spring.version}

org.springframework

spring-tx

${spring.version}

org.springframework

spring-jdbc

${spring.version}

org.springframework

spring-webmvc

${spring.version}

org.springframework

spring-aop

${spring.version}

org.springframework

spring-context-support

${spring.version}

org.springframework

spring-test

${spring.version}

org.springframework

spring-aspects

${spring.version}

commons-fileupload

commons-fileupload

1.3.1

commons-io

commons-io

2.2

commons-codec

commons-codec

1.9

org.slf4j

slf4j-api

${slf4j.version}

org.slf4j

slf4j-log4j12

${slf4j.version}

javax.servlet

jstl

1.2

javax

javaee-api

provided

7.0

testfile

maven-clean-plugin

3.0.0

maven-resources-plugin

3.0.2

maven-compiler-plugin

3.7.0

maven-surefire-plugin

2.20.1

maven-war-plugin

3.2.0

maven-install-plugin

2.5.2

maven-deploy-plugin

2.8.2

配置好pom,然后就来对springMVC进行相关的配置,首先按照如下的格式创建好对应的文件,里面的配置一一来说明:

ac467239d991ac5f5c381f3d30208642.png

1.首先是log4j.properties见上面的配置即可,拷贝到里面并保存;

2.然后是springMVC的配置:

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"

xmlns:context="http://www.springframework.org/schema/context"

xmlns:mvc="http://www.springframework.org/schema/mvc"

xsi:schemaLocation="http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans-3.1.xsd

http://www.springframework.org/schema/context

http://www.springframework.org/schema/context/spring-context-3.1.xsd

http://www.springframework.org/schema/mvc

http://www.springframework.org/schema/mvc/spring-mvc.xsd">

class="org.springframework.web.servlet.view.InternalResourceViewResolver">

class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

具体配置的内容包括启用注解功能,定义springMVC的视图解析器,定义上传文件的大小和编码;

3.其次是user-setting.properties 里面具体内容见上面的用户配置,主要限定了上传文件的类型和大小的问题;

4.最后是对web.xml进行配置:

/p>

"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"

"http://java.sun.com/dtd/web-app_2_3.dtd" >

Archetype Created Web Application

SpringMVC

org.springframework.web.servlet.DispatcherServlet

contextConfigLocation

classpath:spring-mvc.xml

1

SpringMVC

/

具体包括定义spring的分发器,指定springMVC文件配置的位置,以及servlet映射的地址;

这样我们的SpringMVC的开发环境算是搭建完成了。

2.下面将我们的工具类拷贝到项目中的自己指定的位置:

a04b1f407299943f0996336d1ba1861d.png

3.下面开始正式对我们的工具类进行上传文件和下载文件的测试了:

1).首先编写index.jsp页面:

e7a1f5af7bb1a9b12798161ca2c4dbb9.png

Created by IntelliJ IDEA.

User: chenpeng

Date: 2018/7/21

Time: 17:03

To change this template use File | Settings | File Templates.

--%>

Title

选择文件:

这样页面的效果为:

c3ed59b98a77381af2620d43540f5d3a.png

接着我们来编写springMVC的后台:

package com.baosight.controller;

import com.baosight.utils.MyfileUtils;

import org.springframework.context.annotation.Scope;

import org.springframework.http.ResponseEntity;

import org.springframework.stereotype.Controller;

import org.springframework.ui.ModelMap;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

import org.springframework.web.bind.annotation.RequestParam;

import org.springframework.web.bind.annotation.ResponseBody;

import org.springframework.web.multipart.MultipartFile;

import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

import java.io.IOException;

import java.util.List;

@Controller

@Scope("prototype")

@RequestMapping("/")

public class UploadFileTest {

/**

* 上传文件测试

* @param files

* @param map

* @return

*/

@RequestMapping(value = "/upload",method = RequestMethod.POST)

public String upload(@RequestParam("files") MultipartFile[] files, ModelMap map){

List results = MyfileUtils.uploadFile(files,"ds/sd","测试上传的文件");

if(results!=null && results.size()>0){

map.addAttribute("urls", results.get(0));

}

return "success";

}

/**

* 下载文件测试

* @param url

* @return

* @throws IOException

*/

@RequestMapping(value = "/download")

public ResponseEntity getFile(@RequestParam("url")String url) throws IOException {

return MyfileUtils.downloadFile(url,"下载的文件"+ url.substring(url.lastIndexOf(".")));

}

}

下载成功的页面的jsp为:

d9d3bba4c2b088ca6ffbbf5bc1701d1b.png

Title

success!

下载上传的文件

里面提供了下载的按钮(根据我们SpringMVC的视图解析器的配置我们的所有页面都在WEB-INF/views/文件夹下)。

特别注意的是页面上要启用el表达式否则el表达式在页面上会失效!到现在为止,我们的代码工作已经编写完成了,接着进行测试:

a69bae0a483e9119b8222ae234151159.png

02c4b14d0f65e9be2e54eada7f7be762.png

e33ec1b78b32077c98a96cb817cae023.png

08ba1c3787d1fd07ba7f5e9e8ceeef83.png

这样我们文件上传和下载的任务就算完成了。

备注:

1.用户可以再user-setting.properties中指定文件存放的更目录

2.用户在上传文件还可以指定次级目录,比如根目录+(次级目录)+(新指定的文件名).文件后缀

3.文件都是保存在服务器内部的,能够保存小量的文件对于大型的文件需要考虑其他专门的文件存储的解决方案,本工具类能够实现中小型项目文件上传和下载的任务。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值