</pre>文件上传做一个笔记。<p></p><p>页面导入fileupload的插件包 jquery.fileupload.js、jquery.fileupload-process.js、jquery.fileupload-validate.js;</p><p>放一个input的元素 </p><p></p><pre name="code" class="html"><form class="hide">
<input id="fileupload" type="file" name="imageFile" />
</form>
js代码
$('#'+fileinputid).fileupload({
url:window.contextPath+url,
type : 'POST',
dataType : 'json',
progressall: function (e, data) {//进度条
//console.log(data);
var progress = parseInt(data.loaded / data.total * 100, 10);
$('.progress .progress-bar').css(
'width',
progress + '%'
);
$('.progress .progress-bar').text(progress + '%');
},
add:function(e,data){//在选中文件开始上传之前添加一个进度条的显示域
var html = '<div class="modal fade" id="myModal">\
<div class="modal-dialog" >\
<div class="modal-content">\
<div class="modal-body">\
<div class="progress">\
<div class="progress-bar" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100">\
0%\
</div>\
</div>\
</div>\
</div>\
</div>\
</div>';
$('body').append(html);
$('#myModal').modal();
data.submit();
},
done : function(e, data) {
$("#myModal").remove();
if (data._response.result.success) {
callback(data);
} else {
ZL.alert("faild");
}
}});
java后台代码的处理
/**
* 文件上传
*
* @param module 模块名,对应文件目录
* @param imageFile 上传的文件流
* @return
*/
@RequestMapping(value = {"/file/{module}/upload.sj"})
@ResponseBody
public ResultView upload(@PathVariable String module, MultipartFile imageFile) {
ResultView rv = new ResultView();
rv.setMsg("上传文件失败!");
try {
if (null != imageFile) {
String filepath = saveRsource(module, imageFile);
rv.setSuccess(true);
rv.setData(filepath);
}
} catch (IOException e) {
logger.error(e.getLocalizedMessage(), e);
}
return rv;
}
/**
* 保存文件
*
* @param module 目录名
* @param userFile 文件流
* @return
* @throws IOException
*/
private String saveRsource(String module, MultipartFile userFile) throws IOException {
String originalFilename = userFile.getOriginalFilename(); // 原始文件名
String fileName = UUIDGenerator.getUUID() + "." + FileUtils.getFileExtension(originalFilename); // 存储文件名
String relativePath = module + "/" + DateUtils.format(new Date(), DateUtils.YYYYMM) + "/" + fileName; // 相对路径
String filePath = fileService.getFileserver() + relativePath;// 绝对路径
File file = new File(filePath);
if (!file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
FileCopyUtils.copy(userFile.getBytes(), file);
return originalFilename + "," + relativePath;
}