mark一下以防自己以后再次遇到,也是给同行们一个参考。先说下我的需求:
前端我需要给用户一个上传文件页面,用户点击上传后,不会像提交form一样跳转,而是在上传页面下方显示上传情况(正在分析/上传出现错误/上传成功),当然首选ajax来实现了
后端的话我拿到文件,将它保存在一个临时位置,待我分析完毕上传DB后,将临时文件删除。所以我这里并不是简单的文件上传,中间还要将原始文件进行一个分析再保存,并且将原始文件删除。
ok,
先从前端搞起:
我前端是用React写的,先贴源码:
import React from 'react';
import $ from 'jquery';
export default class Upload extends React.Component {
constructor(props) {
super(props);
this.state = {infor: ''};
this.uploadvcf = this.uploadvcf.bind(this);
}
uploadvcf(e) {
e.preventDefault(); //取消form的默认提交功能,只响应该uploadvcf()
this.setState({infor: 'file is analyzing in back-end, please waiting.....'});
const form = $('form')[0];
const data = new FormData(form); //这里要设置
$.ajax({
type: 'POST',
encType: 'multipart/form-data', //表明上传类型为文件
processData: false, //这里设置成false,表明上传数据不需转换成字符串
contentType: false,
cache: false,
url: 'uploadvcf',
data: data,
success: response => {
this.setState({infor:response});
}
});
}
render() {
return (
<div className="container">
<div className="row">
<div className="col-md-offset-1 col-md-11">
<h3>Upload File</h3>
<div className="col-md-8">
<form className="" method="POST"> //form
<div className="form-group">
<label>File1</label>
<input type="file" className="form-control" name="files"/>
</div>
<div className="form-group">
<label>File2</label>
<input type="file" className="form-control" name="files"/>
</div>
<div className="form-group">
<label>File3</label>
<input type="file" className="form-control" name="files"/>
</div>
<div className="col-md-offset-8 col-md-4">
<button className="btn btn-primary" onClick={this.uploadvcf}>Submit</button>
</div>
</form>
<div>
<h4></h4>
</div>
</div>
<div className="col-md-8">
<h4 id="info">{this.state.infor}</h4>
</div>
</div>
</div>
</div>
);
}
}
上传页面:
再说后端:
先贴源码:
@RequestMapping(value="uploadvcf", method=RequestMethod.POST)
public @ResponseBody String uploadFile(@RequestParam("files") MultipartFile[] files, HttpServletRequest request) {
if(files != null && files.length>0) { //循环每一个文件
for(int i=0; i<files.length;i++) {
MultipartFile file = files[i];
try {
analyzeFile(file); //分析文件,方法在下边
} catch (IllegalArgumentException e) {
e.printStackTrace();
return "file format is error";
} catch (Exception e) {
return "analyzing error when analyzing " + file.getOriginalFilename();
}
}
return "upload successfully";
} else {
return "You failed to upload because the files is empty";
}
}
//分析方法
private void analyzeFile(MultipartFile file) throws Exception {
if(!file.isEmpty()) {
String filePath = request.getSession().getServletContext().getRealPath("/") + "upload/"; //声明一个临时文件保存路径
File dir = new File(filePath);
if(! dir.exists()) {
dir.mkdir();
} //假如路径不存在 生成
String path = filePath + file.getOriginalFilename();
File tempFile = null;
//save to the /upload path
try {
tempFile = new File(path);
file.transferTo(tempFile);//将上传的文件保存到临时文件
//analyze the file
pointService.uploadFile(path);
tempFile.delete(); //分析完成,删除临时文件
} finally {
tempFile.delete(); //假如分析过程出错,也要删除临时文件
}
}
}
嗯,大约就是这样子。mark下