springmvc的上传和下载功能
上传
步骤
-
选择文件:
在页面上用input控件, type=“file”;
HTML代码如下:
<input type="file" class="form-control input-w" id="myfile">
-
文件上传:
form表单提交: form添加 enctype=“multipartlform-data” 属性
ajax提交: data类型formData append(“myfile”,$(" #myfle")[0] files[0]);
JavaScript代码如下:var formData = new FormData(); fileName = $("#fileName").val(); fileIntroduce = $("#fileIntroduce").val(); if(fileName == null || fileName == ""){ new $.zui.Messager('文件名不能为空', { type: 'danger' // 定义颜色主题 }).show(); return; } formData.append("fileName",fileName); formData.append("fileIntroduce",fileIntroduce); formData.append("id",id); formData.append("myfile",$("#myfile")[0].files[0]); $.ajax({ url:'uploadFile.ajax', type:'post', data: formData, dataType:'JSON', contentType: false, processData: false, success:function(resultJosn){ } })
- 文件接收:
在springMVC配置 文件中配置上传的bean对象类
在Controller端用MultipartFile获取文件对象file
file.isEmpty()判断文件是否为空
file.getOriginalFilename()取得文件名
f.exists()判断路径是否存在 f.mkdirs()逐级创建文件
java 代码如下:
/**
* 上传文件并添加到数据库
* @param myfile
* @return bean对象
* @throws Exception
*/
@RequestMapping("uploadFile.ajax")
public ResultType uploadFile(MultipartFile myfile,String fileName,String fileIntroduce,Integer id) throws Exception{
ResultType result = new ResultType();
if(myfile == null || myfile.isEmpty()) {
result.setResultType(0);
result.setMsg("上传的文件不能为空!");
return result;
}
String name = myfile.getOriginalFilename();
//存放地址
String path = "d:/down/"+name;
java.io.File f = new java.io.File(path);
if(!f.exists()) {
f.mkdirs();
}
List<DocType> docTypeList = ds.selectDocType();
String fileSuffix = FileSuffixUtils.getFileSuffix(name);
File file = new File(null,null,id,fileName,0,"未审核",path,new Date(),null);
//后缀判断是否可以上传
for (DocType d:docTypeList) {
if(d.getTyName().equals(fileSuffix)) {
myfile.transferTo(f);
result.setResultType(1);
file.setTypeId(d.getTyId());
fs.addFile(file);
return result;
}
}
result.setResultType(0);
result.setMsg("该类型文件暂时不能上传!");;
return result;
}
- 保存文件:
file transferTo(路径)String path = "d:/down/"+name; java.io.File f = new java.io.File(path); myfile.transferTo(f);
下载
步骤
- 请求controller
- 业务取得下载的路径
- 输出流new出对象和定义传输类型,输出对象和并关闭流
- 接收下载请求进行下载
具体 JAVA 代码如下:
/**
* 文件的下载
* @param request 请求
* @param response 返回
* @param id 文件的ID
* @throws IOException
*/
@RequestMapping("downloadFile.ajax")
public void downloadFile(HttpServletRequest request, HttpServletResponse response,Integer id) throws IOException{
List<File> fileList = fs.selectFile(0, 1, null, id, null, null, null, null, null);
File file = fileList.get(0);
String fileName = FileSuffixUtils.getFileName(file.getPath());
String filePath = file.getPath();
response.setCharacterEncoding("utf-8");
response.setContentType("multipart/form-data");
response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
//打开本地文件流
InputStream inputStream = new FileInputStream(filePath);
//激活下载操作
OutputStream os = response.getOutputStream();
//循环写入输出流
byte[] b = new byte[2048];
int length;
while ((length = inputStream.read(b)) > 0) {
os.write(b, 0, length);
}
// 这里主要关闭。
os.close();
inputStream.close();
}
(有错误的地方欢迎指出)