08.文件上传和下载示例
1.导包
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
2.控制器中配置上传解析器
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="5000000"/>
<property name="defaultEncoding" value="utf-8"></property>
</bean>
3.上传form表单属性
<form action="upload.do" enctype="multipart/form-data" method="post">
4.控制器controller参数接收
@RequestParam("userfile") MultipartFile uploadFile
5.MultipartFile拥有方法如下:
String getOriginalFilename():
String getContentType();
long getSize();
String getName()
6.保存到电脑盘符中
File dir = new File("d:/upload");
dir.mkdir();
File file=new File(dir, uploadFile.getOriginalFilename());
//将上载文件保存到文件中
uploadFile.transferTo(file);
7.保存到服务器路径中
String path="/upload";//WEB路径
path = request.getServletContext().getRealPath(path);
System.out.println(path);
//创建upload文件夹
File dir = new File(path);
dir.mkdir();
File file=new File(dir, uploadFile.getOriginalFilename());
//将上载文件保存到文件中
uploadFile.transferTo(file);
8.多文件上传
var uploadFiles=$("#upload-files");
var ajaxBtn=$("#jquery_upload");
ajaxBtn.click(function(){
var url="upload.do";
var data=new FormData();
var files = uploadFiles[0].files;
for(var i=0; i<files.length; i++){
var f = files[i];
//uploadFiles对应于控制器接收到的RequestParam("uploadFiles")必须相互对应,否则发生400错误
data.append("uploadFiles", f,f.name);
}
console.log(data)
$.ajax({
url:url,
type:"POST",
data:data,
dataType:"json",
processData:false, //不要处理 data数据!!!
contentType:false, //不要由JQuery设定ContentType
success:function(json){
ajaxBtn.val("JQuery 上载");
}
});
});
10.多文件上传对应的控制器代码:
@RequestMapping(value="/upload.do", method=RequestMethod.POST)
@ResponseBody
public ResponseResult<Void> uploadHandler(@RequestParam("uploadFiles") MultipartFile[] uploadFiles,HttpServletRequest request) throws IllegalStateException, IOException{
System.out.println(uploadFiles.toString());
//保存到文件系统
String path="/upload";//WEB路径
path = request.getServletContext().getRealPath(path);
System.out.println(path);
//创建upload文件夹
File dir = new File(path);
if(!dir.exists()){
dir.mkdir();
}
for(MultipartFile uploadFile:uploadFiles){
File file=new File(dir, uploadFile.getOriginalFilename());
//将上载文件保存到文件中
System.out.println(uploadFile);
uploadFile.transferTo(file);
}
ResponseResult<Void> rr=new ResponseResult<Void>();
rr.setStatus(ResponseResult.STATUS_OK);
rr.setMessage("上载成功");
return rr;
}
11.文件下载
@RequestMapping(value="download.do",produces="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
@ResponseBody
public ResponseEntity<byte[]> download(HttpServletRequest request,HttpServletResponse response,@RequestParam("filename") String filename) throws IOException{
//下载文件路径
String path = request.getServletContext().getRealPath("/");
System.out.println(path);
File file = new File(path + File.separator + filename);
System.out.println(file);
HttpHeaders headers = new HttpHeaders();
//下载显示的文件名,解决中文名称乱码问题
String downloadFielName = new String(filename.getBytes("UTF-8"),"iso-8859-1");
//通知浏览器以attachment(下载方式)打开图片
headers.setContentDispositionFormData("attachment", downloadFielName);
//application/octet-stream : 二进制流数据(最常见的文件下载)。
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers, HttpStatus.CREATED);
文件上传和下载最终版本:
js代码:
var uploadFiles=$("#upload-files");
$("#saveUploadBtn").click(function(){
console.log(uploadFiles)
var url="upload";
var data=new FormData();
var pathArray=new Array();
var files = uploadFiles[0].files;
for(var i=0; i<files.length; i++){
var f = files[i];
console.log(f.webkitRelativePath)
data.append("uploadFiles", f,f.name);
pathArray[i]=(f.webkitRelativePath);
}
console.log(data)
$.ajax({
url:url,
type:"POST",
data:data,
dataType:"json",
processData:false,
contentType:false,
success:function(obj){
alert(obj.message)
}
});
});
$("#upload-files").blur(function(){
var url="uploadPath";
var data=new FormData();
var pathArray=new Array;
var files = uploadFiles[0].files;
for(var i=0; i<files.length; i++){
var f = files[i];
console.log(f.webkitRelativePath)
alert(f.val())
pathArray.push({"path":f.webkitRelativePath});
}
console.log(pathArray+"11111")
$.ajax({
url:url,
type:"POST",
data: JSON.stringify(pathArray),
dataType:"json",
processData:false,
// contentType:false,
contentType:"application/json",
success:function(obj){
}
});
});
控制器代码:
package org.svnadmin.controller.fileupload;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
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.svnadmin.common.entity.ResponseResult;
@Controller
@RequestMapping("/")
public class FileUploadController {
//pathList:前端input传递过来的原始系统路径
private List<Object> pathList=new ArrayList<Object>();
//pathHandlerList:已经处理好的原始文件路径,处理好的保存路径封装在pathHandlerList中
private List<String> pathHandlerList=new ArrayList<String>();
/**
* 处理上传文件保存,对应于file_upload.js中的上传异步请求
* @param uploadFiles
* @param request
* @return
*/
@RequestMapping(value="/upload", method=RequestMethod.POST)
@ResponseBody
public ResponseResult<Void> fileUploadHandler(@RequestParam("uploadFiles") MultipartFile[] uploadFiles,HttpServletRequest request) {
try {
//处理路径
handPath();
System.out.println(pathList.size());
System.out.println(pathHandlerList.size());
for (int i = 0; i < pathHandlerList.size(); i++) {
System.out.println(pathHandlerList.get(i));
//path = request.getServletContext().getRealPath(path);
File dir = new File(pathHandlerList.get(i));
if(!dir.exists()){
dir.mkdirs();
}
//保存上传文件
File file=new File(dir, uploadFiles[i].getOriginalFilename());
uploadFiles[i].transferTo(file);
}
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
ResponseResult<Void> rr=new ResponseResult<Void>();
rr.setStatus(ResponseResult.STATUS_OK);
rr.setMessage("上载成功");
return rr;
}
/**
* 处理保存文件路径
* path:保存仓库的初始位置,待修改
*/
private void handPath() {
String path=null;
for(int i=0;i<pathList.size();i++){
path="D:"+File.separator+"Repositories"+File.separator+"myRepositories"+File.separator;
String[] str=pathList.get(i).toString().substring(6, pathList.get(i).toString().lastIndexOf("/")).split("/");
for (int j = 0; j < str.length; j++) {
path+=str[j]+File.separator;
}
pathHandlerList.add(path);
}
}
/**
* 接收上传全部路径的对应的控制器方法
* @param list
* @return
*/
@RequestMapping(value="uploadPath")
@ResponseBody
public List<Object> uploadPathHandler(@RequestBody List<Object> list){
pathList=list;
return pathList;
}
@RequestMapping("/import.do")
@ResponseBody
public ResponseResult<Void> importHandler(String importUrl,String importPath){
System.out.println(importUrl);
System.out.println(importPath);
ResponseResult<Void> rr=new ResponseResult<Void>();
rr.setStatus(ResponseResult.STATUS_OK);
rr.setMessage("上载成功");
return rr;
}
}
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
2.控制器中配置上传解析器
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="5000000"/>
<property name="defaultEncoding" value="utf-8"></property>
</bean>
3.上传form表单属性
<form action="upload.do" enctype="multipart/form-data" method="post">
4.控制器controller参数接收
@RequestParam("userfile") MultipartFile uploadFile
5.MultipartFile拥有方法如下:
String getOriginalFilename():
String getContentType();
long getSize();
String getName()
6.保存到电脑盘符中
File dir = new File("d:/upload");
dir.mkdir();
File file=new File(dir, uploadFile.getOriginalFilename());
//将上载文件保存到文件中
uploadFile.transferTo(file);
7.保存到服务器路径中
String path="/upload";//WEB路径
path = request.getServletContext().getRealPath(path);
System.out.println(path);
//创建upload文件夹
File dir = new File(path);
dir.mkdir();
File file=new File(dir, uploadFile.getOriginalFilename());
//将上载文件保存到文件中
uploadFile.transferTo(file);
8.多文件上传
var uploadFiles=$("#upload-files");
var ajaxBtn=$("#jquery_upload");
ajaxBtn.click(function(){
var url="upload.do";
var data=new FormData();
var files = uploadFiles[0].files;
for(var i=0; i<files.length; i++){
var f = files[i];
//uploadFiles对应于控制器接收到的RequestParam("uploadFiles")必须相互对应,否则发生400错误
data.append("uploadFiles", f,f.name);
}
console.log(data)
$.ajax({
url:url,
type:"POST",
data:data,
dataType:"json",
processData:false, //不要处理 data数据!!!
contentType:false, //不要由JQuery设定ContentType
success:function(json){
ajaxBtn.val("JQuery 上载");
}
});
});
10.多文件上传对应的控制器代码:
@RequestMapping(value="/upload.do", method=RequestMethod.POST)
@ResponseBody
public ResponseResult<Void> uploadHandler(@RequestParam("uploadFiles") MultipartFile[] uploadFiles,HttpServletRequest request) throws IllegalStateException, IOException{
System.out.println(uploadFiles.toString());
//保存到文件系统
String path="/upload";//WEB路径
path = request.getServletContext().getRealPath(path);
System.out.println(path);
//创建upload文件夹
File dir = new File(path);
if(!dir.exists()){
dir.mkdir();
}
for(MultipartFile uploadFile:uploadFiles){
File file=new File(dir, uploadFile.getOriginalFilename());
//将上载文件保存到文件中
System.out.println(uploadFile);
uploadFile.transferTo(file);
}
ResponseResult<Void> rr=new ResponseResult<Void>();
rr.setStatus(ResponseResult.STATUS_OK);
rr.setMessage("上载成功");
return rr;
}
11.文件下载
@RequestMapping(value="download.do",produces="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet")
@ResponseBody
public ResponseEntity<byte[]> download(HttpServletRequest request,HttpServletResponse response,@RequestParam("filename") String filename) throws IOException{
//下载文件路径
String path = request.getServletContext().getRealPath("/");
System.out.println(path);
File file = new File(path + File.separator + filename);
System.out.println(file);
HttpHeaders headers = new HttpHeaders();
//下载显示的文件名,解决中文名称乱码问题
String downloadFielName = new String(filename.getBytes("UTF-8"),"iso-8859-1");
//通知浏览器以attachment(下载方式)打开图片
headers.setContentDispositionFormData("attachment", downloadFielName);
//application/octet-stream : 二进制流数据(最常见的文件下载)。
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),headers, HttpStatus.CREATED);
文件上传和下载最终版本:
js代码:
var uploadFiles=$("#upload-files");
$("#saveUploadBtn").click(function(){
console.log(uploadFiles)
var url="upload";
var data=new FormData();
var pathArray=new Array();
var files = uploadFiles[0].files;
for(var i=0; i<files.length; i++){
var f = files[i];
console.log(f.webkitRelativePath)
data.append("uploadFiles", f,f.name);
pathArray[i]=(f.webkitRelativePath);
}
console.log(data)
$.ajax({
url:url,
type:"POST",
data:data,
dataType:"json",
processData:false,
contentType:false,
success:function(obj){
alert(obj.message)
}
});
});
$("#upload-files").blur(function(){
var url="uploadPath";
var data=new FormData();
var pathArray=new Array;
var files = uploadFiles[0].files;
for(var i=0; i<files.length; i++){
var f = files[i];
console.log(f.webkitRelativePath)
alert(f.val())
pathArray.push({"path":f.webkitRelativePath});
}
console.log(pathArray+"11111")
$.ajax({
url:url,
type:"POST",
data: JSON.stringify(pathArray),
dataType:"json",
processData:false,
// contentType:false,
contentType:"application/json",
success:function(obj){
}
});
});
控制器代码:
package org.svnadmin.controller.fileupload;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
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.svnadmin.common.entity.ResponseResult;
@Controller
@RequestMapping("/")
public class FileUploadController {
//pathList:前端input传递过来的原始系统路径
private List<Object> pathList=new ArrayList<Object>();
//pathHandlerList:已经处理好的原始文件路径,处理好的保存路径封装在pathHandlerList中
private List<String> pathHandlerList=new ArrayList<String>();
/**
* 处理上传文件保存,对应于file_upload.js中的上传异步请求
* @param uploadFiles
* @param request
* @return
*/
@RequestMapping(value="/upload", method=RequestMethod.POST)
@ResponseBody
public ResponseResult<Void> fileUploadHandler(@RequestParam("uploadFiles") MultipartFile[] uploadFiles,HttpServletRequest request) {
try {
//处理路径
handPath();
System.out.println(pathList.size());
System.out.println(pathHandlerList.size());
for (int i = 0; i < pathHandlerList.size(); i++) {
System.out.println(pathHandlerList.get(i));
//path = request.getServletContext().getRealPath(path);
File dir = new File(pathHandlerList.get(i));
if(!dir.exists()){
dir.mkdirs();
}
//保存上传文件
File file=new File(dir, uploadFiles[i].getOriginalFilename());
uploadFiles[i].transferTo(file);
}
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
ResponseResult<Void> rr=new ResponseResult<Void>();
rr.setStatus(ResponseResult.STATUS_OK);
rr.setMessage("上载成功");
return rr;
}
/**
* 处理保存文件路径
* path:保存仓库的初始位置,待修改
*/
private void handPath() {
String path=null;
for(int i=0;i<pathList.size();i++){
path="D:"+File.separator+"Repositories"+File.separator+"myRepositories"+File.separator;
String[] str=pathList.get(i).toString().substring(6, pathList.get(i).toString().lastIndexOf("/")).split("/");
for (int j = 0; j < str.length; j++) {
path+=str[j]+File.separator;
}
pathHandlerList.add(path);
}
}
/**
* 接收上传全部路径的对应的控制器方法
* @param list
* @return
*/
@RequestMapping(value="uploadPath")
@ResponseBody
public List<Object> uploadPathHandler(@RequestBody List<Object> list){
pathList=list;
return pathList;
}
@RequestMapping("/import.do")
@ResponseBody
public ResponseResult<Void> importHandler(String importUrl,String importPath){
System.out.println(importUrl);
System.out.println(importPath);
ResponseResult<Void> rr=new ResponseResult<Void>();
rr.setStatus(ResponseResult.STATUS_OK);
rr.setMessage("上载成功");
return rr;
}
}