以前没有写过过文件方面的代码= =,简直菜的要死。。。
用的jQuery的异步上传
$.ajaxFileUpload({
url: '后台处理的controller请求路径',
secureuri:false,secureuri:false,
fileElementId: 'id',
type: 'post',
dataType: 'json',
success : function(data, status) {
data = $.parseJSON(data);//字符创 转为 json对象
},
error: function (data, status, e){//服务器响应失败处理函数
}
});
},
error: function (data, status, e){//服务器响应失败处理函数
}
});
controller中可以获得List<MultipartFile> uploadFiles,遍历uploadFiles
for(MultipartFile uploadFile: uploadFiles){
String fileName = uploadFile.getOriginalFilename();
String filePath = basePath + fileName;
File upFile = new File(basePath);//创建指定路径的文件
if(!upFile.isDirectory()){//判断文件夹是否存在 不存在创建
upFile.mkdirs();
}
uploadFile.transferTo(new File(""));//上传文件
}
文件下载:
public void downloadFile(HttpServletResponse response, @RequestParam("materialPath")String path, boolean isOnline) throws IOException{
File f= new File(path);
String fileName = f.getName();
if(!f.exists()){
response.sendError(404, "File not Found");
return ;
}
BufferedInputStream br = new BufferedInputStream(new FileInputStream(f));
byte [] buf = new byte[1024];
int len = 0;
response.reset();
if(isOnline){
//在线打开
URL u = new URL("file:///" + path);
response.setContentType(u.openConnection().getContentType());
response.setHeader("Content-Disposition" ,"inline; filename=" + fileName);//页面中打开
}else{
//纯下载
response.setContentType("application/x-msdownload");
//文件名是中文名需要转码
response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, "UTF-8"));
}
OutputStream out = response.getOutputStream();
while((len = br.read(buf)) > 0){
out.write(buf, 0, len);
}
br.close();
out.close();
}
URLEncoder.encode(fileName, "UTF-8"));
}
OutputStream out = response.getOutputStream();
while((len = br.read(buf)) > 0){
out.write(buf, 0, len);
}
br.close();
out.close();
}
修改ajaxfileupload.js
添加处理方法
handleError: function( s, xhr, status, e ) {
// If a local callback was specified, fire it
if ( s.error ) {
s.error.call( s.context || s, xhr, status, e );
}
// Fire the global callback
if ( s.global ) {
(s.context ? jQuery(s.context) : jQuery.event).trigger( "ajaxError", [xhr, s, e] );
}
} ,
修改json解析方法
uploadHttpData: function( r, type ) {
var data = !type;
data = type == "xml" || data ? r.responseXML : r.responseText;
// If the type is "script", eval it in global context
if ( type == "script" )
jQuery.globalEval( data );
// Get the JavaScript object, if JSON is used.
if ( type == "json" )
{
// If you add mimetype in your response,
// you have to delete the '<pre></pre>' tag.
// The pre tag in Chrome has attribute, so have to use regex to remove
var data = r.responseText;
}
// evaluate scripts within html
if ( type == "html" )
jQuery("<div>").html(data).evalScripts();
//alert($('param', data).each(function(){alert($(this).attr('value'));}));
return data;
}