码迷,mamicode.com
首页 > 编程语言 > 详细

spring mvc文件上传与下载

时间:2015-04-27 14:50:40      阅读:240      评论:0      收藏:0      [点我收藏+]

标签:

  基于spring mvc注解:

(1)导入jar包:ant.jar、commons-fileupload.jar、connom-io.jar。

(2)在spring-mvc.xml中的配置

<!-- 上传文件拦截,设置最大上传文件大小 10M=10*1024*1024(B)=10485760 bytes -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding" value="UTF-8"></property>
<property name="maxUploadSize" value="${web.maxUploadSize}" />
</bean>

(3)jsp页面

<form:form id="inputForm" modelAttribute="fileReport" action="${ctx}/buss/fileReport/save" method="post" enctype="multipart/form-data" class="form-horizontal" >
<form:hidden path="id"/>
<div class="control-group">
<label class="control-label">文件:</label>
<div class="controls">
<form:input path="file" type="file" htmlEscape="false" class="input-xlarge "/>
</div>
</div>
<input id="btnCancel" class="btn" type="button" value="返 回" onclick="history.go(-1)"/>
</form:form>

(4)FileReport.java

private static final long serialVersionUID = 1L;
private String filePath; // 文件路径
private String fileName; // 文件名
private Product product; // 产品
private byte[] fileData; //文件内容
private MultipartFile file; //文件

(5)数据库表设计:

技术分享

 

(6)FileReportController.java

@Controller
@RequestMapping(value = "${adminPath}/buss/fileReport")
public class FileReportController {

@Autowired
private FileReportService fileReportService;

@Autowired
private FileUtil fileUtil;

//文件上传

@RequiresPermissions("buss:fileReport:edit")
@RequestMapping(value = "save")
public String save(FileReport fileReport, Model model, RedirectAttributes redirectAttributes, HttpServletRequest request) {
if (!beanValidator(model, fileReport)){
return form(fileReport, model);
}

MultipartFile multipartFile = fileReport.getFile();

/*文件上传到服务器 1
if(multipartFile == null) {
fileReportService.save(fileReport);
addMessage(redirectAttributes, "保存文件上传成功");
return "redirect:"+Global.getAdminPath()+"/buss/fileReport/?repage";
}
String filePath = fileUtil.fileUpload(multipartFile, request);
fileReport.setFilePath(filePath);
*/

/*文件上传到服务器 2*/
if(multipartFile == null) {
fileReportService.save(fileReport);
addMessage(redirectAttributes, "保存文件上传成功");
return "redirect:"+Global.getAdminPath()+"/buss/fileReport/?repage";
}
String filePath = fileUtil.uploadFile(multipartFile, request);
fileReport.setFilePath(filePath);

/*文件上传到数据库*
byte[] fileData = fileUtil.fileUploadToServer(multipartFile);
fileReport.setFileData(fileData);
/
*
*/
fileReport.setFileName(multipartFile.getOriginalFilename());
fileReportService.save(fileReport);
addMessage(redirectAttributes, "保存文件上传成功");
return "redirect:"+Global.getAdminPath()+"/buss/fileReport/?repage";

}

//文件下载

@RequiresPermissions("buss:fileReport:edit")
@RequestMapping(value = "download")
public void downLoad(FileReport fileReport, HttpServletRequest request, HttpServletResponse response) {
//准备数据
FileReport fp = fileReportService.get(fileReport.getId());

//从服务器上下载文件
fileUtil.downLoad(fp, response);


//从数据库下载文件
//fileUtil.downFileFromServer(fp, response);
}

}

(7)添加工具类FileUtil.java

package com.thinkgem.jeesite.modules.buss.web;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import com.thinkgem.jeesite.modules.buss.entity.FileReport;

@Component(value="fileUploadUtil")
public class FileUtil {
public int fileSubPosition(MultipartFile multipartFile) {
return multipartFile.getOriginalFilename().lastIndexOf(".");
}

public String fileName(MultipartFile multipartFile) {
return multipartFile.getOriginalFilename().substring(0, fileSubPosition(multipartFile));
}

public String uploadFile(MultipartFile multipartFile, HttpServletRequest request) {
//如果是Tomcat服务器,创建文件上传的真是目录
String realPath = request.getSession().getServletContext().getRealPath("/upload");
String datePath = new SimpleDateFormat("/yyyy/MM/dd/").format(new Date());
String basePath = realPath + datePath;
File fileDir = new File(basePath);
if(!fileDir.exists()) {
fileDir.mkdirs();
}

//获取文件后缀
String suffix = multipartFile.getOriginalFilename().substring(fileSubPosition(multipartFile));
//构建文件名
String fileName = UUID.randomUUID().toString() + suffix;
//拼成完整的文件保存路径加文件,File.separator文件区分符,相当于\
String filePath = basePath + File.separator + fileName;

/*上传文件
File file = new File(filePath);
try {
multipartFile.transferTo(file);
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
*/

try {
//上传文件
FileUtils.copyInputStreamToFile(multipartFile.getInputStream(), new File(filePath));
} catch (IOException e) {
e.printStackTrace();
}

return filePath;
}

//二进制文件上传到服务器
public String fileUpload(MultipartFile multipartFile, HttpServletRequest request) {
//如果是Tomcat服务器,创建文件上传的真是目录
String realPath = request.getSession().getServletContext().getRealPath("/WEB-INF/upload");
String datePath = new SimpleDateFormat("/yyyy/MM/dd/").format(new Date());
String basePath = realPath + datePath;

File fileDir = new File(basePath);
if(!fileDir.exists()) {
fileDir.mkdirs();
}
//String fileName = multipartFile.getOriginalFilename();
//获取文件后缀
String suffix = multipartFile.getOriginalFilename().substring(fileSubPosition(multipartFile));
String fileName = UUID.randomUUID().toString() + suffix;
String fileNamePath = basePath + fileName;
try {
InputStream is = multipartFile.getInputStream();

// 如果服务器已经存在和上传文件同名的文件,则输出提示信息
File tempFile = new File(fileNamePath);
if (tempFile.exists()) {
boolean delResult = tempFile.delete();
System.out.println("删除已存在的文件:" + delResult);
}
//multipartFile.getSize();
if(!fileName.equals("")) {
FileOutputStream fos = new FileOutputStream(fileNamePath);
byte[] buffer;
if(multipartFile.getSize() < 10485760) {
buffer = new byte[(int) multipartFile.getSize()];
} else {
buffer = new byte[10485760];
}

int count = 0;
// 开始读取上传文件的字节,并将其输出到服务端的上传文件输出流中
while((count=is.read(buffer)) > 0) { //is.read(buffer)此方法从输入流读取一定数量的字节并将它们存储到缓冲区数组b中
fos.write(buffer, 0, count); //1. 向服务端文件写入字节流 ; 2.toClient.write()此方法将指定字节写入此输出流
}

fos.close();
is.close();
}

} catch (IOException e) {
e.printStackTrace();
}
return fileNamePath;
}

//从服务器上以二进制文件下载
public void downLoad(FileReport fp, HttpServletResponse response) {
String path = fp.getFilePath();
String fileName = fp.getFileName();

try {
Long fileLength = new File(path).length();

//清空response
response.reset();
response.setContentType("application/octet-stream;charset=UTF-8");
response.setHeader("Content-Disposition", "attachment;fileName="+ new String(fileName.getBytes("utf-8"), "ISO8859-1"));
response.setHeader("Content-Length", String.valueOf(fileLength));

InputStream fis= new BufferedInputStream(new FileInputStream(path));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();

OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
toClient.write(buffer); //toClient.write()此方法将指定字节写入此输出流
toClient.flush();
toClient.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

//文件上传到数据库
public byte[] fileUploadToServer(MultipartFile multipartFile) {
//获取文件名
byte[] fileData = null;
try {
InputStream is = multipartFile.getInputStream();
if(multipartFile.getSize() < 10485760) {
fileData = new byte[(int)multipartFile.getSize()];
} else {
fileData = new byte[10485760];
}

is.read(fileData);

} catch (IOException e) {
e.printStackTrace();
}
return fileData;

}

//从数据库下载文件
public void downFileFromServer(FileReport fp, HttpServletResponse response) {
byte[] fileData = fp.getFileData();
String fileName = fp.getFileName();
//清空response
response.reset();
response.addHeader("Content-Length", "" + fileData.length);
response.setContentType("application/octet-stream;charset=UTF-8");

try {
response.setHeader("Content-Disposition", "attachment;fileName="+ new String(fileName.getBytes("utf-8"), "ISO8859-1"));
OutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
outputStream.write(fileData);
outputStream.flush();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

spring mvc文件上传与下载

标签:

原文地址:http://www.cnblogs.com/lisang/p/4459776.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!