背景:ssm框架
接下来,我会介绍单文件上传,下载,多文件的上传,下载,使用ajax进行文件的上传下载,和普通的表单提交的文件上传下载。
只要做项目,总是少不了文件的操作,好了废话不多说,直接上代码!
前提:需要在springmvc的配置文件里面加一个文件解析器,这个必须要有!!!
<!-- 定义文件解释器 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 设置默认编码 -->
<property name="defaultEncoding" value="utf-8"></property>
<!-- 上传图片最大大小5M-->
<property name="maxUploadSize" value="5242440"></property>
</bean>
随便提下:需要的jar包,我项目使用的maven构建,直接添加的依赖,jar包是下面两个:
commons-fileupload-1.3.2.jar
commons-io-2.2.jar
一、单文件的文件上传、下载
上传:前台
<form id ="form2" action="load/upload2" enctype="multipart/form-data" method="post">
<input type = "file" name= 'file' />
<input type="text" name="name" value="dzf"/>
<input type="button" id = "button2" value="ajax上传" onclick="fileupload2()">
<input type ="submit" value="直接上传">
</form>
function fileupload2(){
var formData = new FormData($("#form2")[0]);
$.ajax({
url:'load/upload2',
type:'post',
data:formData,
//必须false才会自动加上正确的Content-Type
contentType: false,
//必须false才会避开jQuery对 formdata 的默认处理
//XMLHttpRequest会对 formdata 进行正确的处理
processData: false,
success:function(data){
alert(data);
},
error:function(data){
alert(data);
alert("后台发生异常");
},
cache:false,
async:true
});
}
后台:
/**
* 单个文件上传
* @param request
* @return
*/
@RequestMapping(value="/upload2",produces="text/html;charset=utf-8")
@ResponseBody
private String upload2(@RequestParam("file")CommonsMultipartFile partFile,HttpServletRequest request) {
try {
String path = request.getServletContext().getRealPath("/upload");
String name = request.getParameter("name");
log.info("其他的参数{}",name);
log.info("upload2---------------start---------------------");
log.info("这个临时文件的路径是[{}]", path);
String filename = partFile.getOriginalFilename();
log.info("文件的名字:{}",filename);
File file = new File(path+"/"+filename);
InputStream inputStream = partFile.getInputStream();
FileUtils.copyInputStreamToFile(inputStream, file);
if(inputStream!=null){
inputStream.close();
}
return "文件上传成功!";
} catch (Exception e) {
e.printStackTrace();
return "文件上传失败!";
}
}
下载:前台
<form action="load/down1" name="form3" id = "form3" method="post">
<input type = "submit" value="普通文件下载">
</form>
后台:
/**
* 文件下载
* 单个文件下载
* @param request
* @return
* @throws IOException
*/
@RequestMapping("/down1")
private void down(HttpServletRequest request,HttpServletResponse response) throws IOException {
String path = request.getServletContext().getRealPath("/upload");
File file = new File(path);
File[] files = file.listFiles();
String name = files[0].getName();//随机获取一个文件,实际中按需编写代码
System.out.println("文件的名字:"+name);
response.addHeader("content-disposition", "attachment;filename="+name);
FileUtils.copyFile(files[0], response.getOutputStream());
}
二、多文件的上传和下载
上传-前台:
<form id ="form5" action="load/upload3" enctype="multipart/form-data" method="post">
<input type = "file" name= 'file' />
<input type = "file" name= 'file' />
<input type = "file" name= 'file' />
<input type="text" name="name" value="dzf"/>
<input type="button" id = "button2" value="多文件ajax上传" onclick="fileupload3()">
<input type ="submit" value="多文件直接上传">
</form>
function fileupload3(){
var formData = new FormData($("#form5")[0]);
$.ajax({
url:'load/upload3',
type:'post',
data:formData,
//必须false才会自动加上正确的Content-Type
contentType: false,
//必须false才会避开jQuery对 formdata 的默认处理
//XMLHttpRequest会对 formdata 进行正确的处理
processData: false,
success:function(data){
alert(data);
},
error:function(data){
alert(data);
alert("后台发生异常");
},
cache:false,
async:true
});
}
上传-后台:
/**
* 多个文件上载
* @param request
* @return
*/
@RequestMapping(value="/upload3",produces="text/html;charset=utf-8")
@ResponseBody
private String upload3(@RequestParam("file")CommonsMultipartFile[] partFiles,HttpServletRequest request) {
InputStream inputStream = null;
try {
String path = request.getServletContext().getRealPath("/upload");
String name = request.getParameter("name");
log.info("其他的参数{}",name);
log.info("upload2---------------start---------------------");
log.info("这个临时文件的路径是[{}]", path);
for (int i = 0; i < partFiles.length; i++) {
String filename = partFiles[i].getOriginalFilename();
log.info("文件的名字:{}",filename);
File file = new File(path+"/"+filename);
inputStream = partFiles[i].getInputStream();
FileUtils.copyInputStreamToFile(inputStream, file);
}
if(inputStream!=null){
inputStream.close();
}
return "文件上传成功!";
} catch (Exception e) {
e.printStackTrace();
return "文件上传失败!";
}
}
一次性下载多个文件,我们需要把文件放到一个压缩包里去
下载-前台:
<form action="load/down2" name="form4" id = "form4" method="post">
<input type = "submit" value="压缩文件下载">
</form>
下载-后台:
/**
* 文件下载,一下次下载多个文件
* 思路:先将多个文件压缩到一个压缩包里去,然后传到前台
* @param request
* @return
* @throws IOException
*/
@RequestMapping("/down2")
private void down2(HttpServletRequest request,HttpServletResponse response) throws IOException {
String path = request.getServletContext().getRealPath("/upload");
File file = new File(path);
File[] files = file.listFiles();
File zipFile =new File("test.zip");
if(!zipFile.exists()){
zipFile.createNewFile();
}
String zipName = zipFile.getName();
log.info("压缩文件的名字:{}",zipName);
response.addHeader("Content-Disposition", "attachment;filename="+zipName);
//定义输出类型
// response.setContentType("application/zip");
ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(zipFile));
BufferedInputStream in =null;
log.info("文件的个数{}",files.length);
for(int i = 0;i<files.length;i++){
String name = files[i].getName();
System.out.println("文件的名字:"+name);
ZipEntry zipEntry = new ZipEntry(name);
zip.putNextEntry(zipEntry);
in = new BufferedInputStream(new FileInputStream(files[i]));
int len = 0;
byte [] btyes = new byte[1024*4];
while((len=in.read(btyes))!=-1){
zip.write(btyes, 0, len);
}
}
zip.flush();
zip.close();
in.close();
FileUtils.copyFile(zipFile, response.getOutputStream());
if(zipFile.exists()){
if(zipFile.delete()){
log.info("压缩包删成功!!");
}else{
log.info("压缩包产出失败!!");
} }
}
到此,文件的上传、下载实例代码已经全部结束!