ajaxfileupload大概是因爲很久不更新,所有有不少的問題
1、handlerError not find
這個東西從jQuery1.4之後就已經沒有了,所以需要手動添加到ajaxfileupload.js中
(插在js文件內部)
<span style="color:#ff0000;"> 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] );
}
} ,</span>
createUploadIframe: function(id, uri)
{
//create frame
var frameId = 'jUploadFrame' + id;
2、攜帶參數傳遞文件
因爲ajaxfileupload是創建了form傳遞的,然而作者並沒有把data的內容加入到form中,所以需要手動添加
(紅色部分爲添加的內容,共3處)
<span style="color:#ff0000;">createUploadForm: function(id, fileElementId,data)</span>
{
//create form
var formId = 'jUploadForm' + id;
var fileId = 'jUploadFile' + id;
var form = jQuery('<form action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');
var oldElement = jQuery('#' + fileElementId);
var newElement = jQuery(oldElement).clone();
jQuery(oldElement).attr('id', fileId);
jQuery(oldElement).before(newElement);
jQuery(oldElement).appendTo(form);
//add data to form
<span style="color:#ff0000;">if(data){
for(var i in data){
//alert(i+":"+data[i]);
$('<input type="hidden" name="' + i + '" value="' + data[i] + '" />').appendTo(form);
}
}</span>
//set attributes
jQuery(form).css('position', 'absolute');
jQuery(form).css('top', '-1200px');
jQuery(form).css('left', '-1200px');
jQuery(form).appendTo('body');
return form;
},
<pre name="code" class="javascript"> ajaxFileUpload: function(s) {
// TODO introduce global settings, allowing the client to modify them for all requests, not only timeout
s = jQuery.extend({}, jQuery.ajaxSettings, s);
var id = s.fileElementId;
<span style="color:#ff0000;"> var form = jQuery.createUploadForm(id, s.fileElementId, s.data);</span>
var io = jQuery.createUploadIframe(id, s.secureuri);
var frameId = 'jUploadFrame' + id;
var formId = 'jUploadForm' + id;
3、文件成功上傳,然而返回數據卻進了error
因爲ajaxfileupload的返回參數多了一串<pre>,無法用json格式解析,所以進了error
我的做法是修改了json返回值
uploadHttpData: function( r, type ) {
var data = !type;
data = type == "xml" || data ? r.responseXML : r.responseText;
// ifthe type is "script", eval it in global context
if( type == "script" ){
jQuery.globalEval( data );
}
// Get the JavaScript object, ifJSON is used.
if( type == "json" ){
<span style="color:#ff0000;"> <span style="white-space:pre"> </span>var a = data.indexOf("{");
var b = data.indexOf("}")+1;
data = data.substring(a,b);
//alert(data);</span>
eval("data = " + data);
}
// evaluate scripts within html
if( type == "html" ){
jQuery("<div>").html(data).evalScripts();
}
return data;
}
4、ajaxfileupload攜帶參數傳遞中文亂碼
因爲ajaxfileload默認是以ISO-8859-1編碼,所以在解析的request的時候要轉換成你的編碼格式
(用中文編碼過濾器沒有效果,不懂爲什麼,希望大神指教!!!)
for(FileItem file :files){
String type = file.getContentType();
if(type!=null) continue;
if(file.isFormField()){
// System.out.println(file.getFieldName());
// System.out.println(file.getString());
<span style="color:#ff0000;">if("painter".equals(file.getFieldName().trim())){
painter = new String(file.getString().trim().getBytes("ISO-8859-1"),"utf-8");
}
if("picname".equals(file.getFieldName().trim())){
picname = new String(file.getString().trim().getBytes("ISO-8859-1"),"utf-8");
}
if("userId".equals(file.getFieldName().trim())){
userId = new String(file.getString().trim().getBytes("ISO-8859-1"),"utf-8");
}</span>
}
}
5、有些ajaxfileupload.js中的post、json需要大寫才能生效,版本太多,需要自己查看js文件
附上完整的ajaxfileupload上傳文件代碼
前臺jsp
<span style="white-space:pre"> </span><div class="modal-body">
<div class="form-group">
<label id="label1" class="col-sm-3 control-label">作品名稱</label>
<div class="col-sm-8">
<input type="text" class="form-control" id="input_picname">
<span id="input_picname_msg"></span>
</div>
<label id="label2" class="col-sm-3 control-label"> 作者</label>
<div class="col-sm-8">
<input type="text" class="form-control" id="input_picpain">
<span id="input_picpain_msg"></span>
</div>
<div class="col-sm-8">
<input type="file" name="upfile" class="form-control" id="input_pic" />
<span id="input_pic_msg"></span>
</div>
<!-- <div class="progress_bar"><span class="progress_per"></span></div> -->
</div>
</div>
js文件function addpic() {
var picname = $("#can #input_picname").val();
var picpain = $("#can #input_picpain").val();
var imgURL = $("#input_pic").val();
$("#can #input_picname_msg").html("");
$("#can #input_picpain_msg").html("");
if (picname == "") {
$("#can #input_picname_msg").html("作品名稱不可爲空");
return;
}
if (picpain == "") {
$("#can #input_picpain_msg").html("作者不可爲空");
return;
}
if (imgURL == ""){
alert("請選擇上傳的圖片");
return ;
}
var suffix = imgURL.substr(imgURL.lastIndexOf(".")+1).toLowerCase();
if(suffix!="jpg"&&suffix!="png"&&suffix!="gif"&&suffix!="bmp"&&suffix!="jpeg"){
alert("請上傳圖片格式的文件");
return ;
}
$.ajaxFileUpload({
url:"savepic.do",
type:"POST",
secureuri:false,
data:{painter:picpain,picname:picname,userId:userId,},
fileElementId:'input_pic',
dataType:"json",
success:function(data,status){
alert(data.msg);
toHref("pictrue/toPictrue.do");
},
error:function(data, status, e){
alert("圖片上傳失敗,請檢查網絡後重試");
}
});
}
服務器端Service
public MyResult savePic(HttpServletRequest req){
MyResult result = new MyResult();
//圖片信息
picItem item = new picItem();
String painter = null;
String picname = null;
String userId = null;
String picId = null;
String fileName = null;
Date time = null;
String pictrue = null;
boolean isMultipart = ServletFileUpload.isMultipartContent(req);
DiskFileItemFactory factory = new DiskFileItemFactory();
// ServletContext context = req.getSession().getServletContext();
// //設置臨時文件存放地址
// factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
ServletFileUpload upload = new ServletFileUpload(factory);
try {
//set request encoding
// req.setCharacterEncoding("utf-8");
//獲取request中的信息
// upload.parseRequest(req);
// MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) req;
// List<MultipartFile>files = mRequest.getFiles("file");
// System.out.println(files.size());
// for(MultipartFile file :files){
List<FileItem> files = upload.parseRequest(req);
// System.out.println(files);
// System.out.println(files.size());
for(FileItem file :files){
String type = file.getContentType();
if(type!=null) continue;
if(file.isFormField()){
// System.out.println(file.getFieldName());
// System.out.println(file.getString());
if("painter".equals(file.getFieldName().trim())){
painter = new String(file.getString().trim().getBytes("ISO-8859-1"),"utf-8");
}
if("picname".equals(file.getFieldName().trim())){
picname = new String(file.getString().trim().getBytes("ISO-8859-1"),"utf-8");
}
if("userId".equals(file.getFieldName().trim())){
userId = new String(file.getString().trim().getBytes("ISO-8859-1"),"utf-8");
}
}
}
//System.out.println(new String(picname.getBytes("ISO-8859-1"),"utf-8"));
for(FileItem file :files){
String type = file.getContentType();
if(type==null){
continue;
}
picId = acgUtil.createId();
time = new Date();
String rootUrl = new SimpleDateFormat("yyyyMMdd").format(time);
String name = new SimpleDateFormat("HHmmss").format(time);
fileName = rootUrl+name+userId+".jpg";
//獲得文件儲存路徑
String realPath = sc.getRealPath("/");
realPath +="img/";
realPath +=(rootUrl+"/");
//創建文件目錄
File dir = new File(realPath);
if(!dir.exists()){
dir.mkdirs();
}
//創建文件對象
File f = new File(realPath,fileName);
if(f.exists()){
f.delete();
}
//創建文件
f.createNewFile();
// file.transferTo(f);
file.write(f);
pictrue = "../img/"+rootUrl+"/"+fileName;
//add pictrue message to mysql
item.setPictrue(pictrue);
item.setPainter(painter);
item.setPicname(picname);
item.setPictime(new Timestamp(time.getTime()));
item.setPic_id(picId);
item.setSubuser_id(userId);
picDao.savePic(item);
}
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("圖片上傳失敗",e);
}
result.setStatus(0);
result.setMsg("圖片上傳成功");
return result;
}