ajaxfileupload.js 文件上传
一,前台代码。
<input id="fileToUpload" type="file" size="25" name="fileToUpload" class="input">
<button class="button" id="buttonUpload" onclick="return ajaxFileUpload();">上传技术文件</button>
function ajaxFileUpload(){
$(‘#bjhlist‘).form(‘submit‘,{
url:‘‘,
onSubmit:function(){
return true;
},
success:function(userMsg){
var userMsg = eval("(" + userMsg + ")");
var guid = userMsg.saveflag;
$("#ggdIdList").val(userMsg.saveflag);
$.ajaxFileUpload(
{
url:‘‘,
secureuri:false,
fileElementId:‘fileToUpload‘,
dataType: ‘json‘,
data:[{‘name‘:‘logan‘,‘id‘:‘id‘}],
success: function (data, status)
{
if(data.isNull != null && data.isNull != ‘‘ ){
parent.$.messager.alert("技术文件上传",data.isNull);
return;
}
if(data.isExection != null && data.isExection != ‘‘ ){
parent.$.messager.alert("技术文件上传",data.isExection);
return;
}
if(data.error != null && data.error != ‘‘ ){
parent.$.messager.alert("技术文件上传",data.error);
return;
}
if(data.success != null && data.success != ‘‘ ){
parent.$.messager.progress({
title:"技术文件上传",
msg:data.success
});
setTimeout(function(){
parent.$.messager.progress(‘close‘);
},1500);
}
},
error: function (data, status, e){
alert(e);
}
}
);
},
error:function(){alert("error");}
});
return false;
};
二,后台代码。
@ResponseBody
@RequestMapping(value="civilapplyFileLoad.html",method=RequestMethod.POST)
public Map<String,String> civilapplyFileLoad(String GgdId,HttpServletRequest request,HttpServletResponse response,@RequestParam("fileToUpload") MultipartFile fileToUpload){
response.setContentType("text/html");
Map<String,String> map = new HashMap<String, String>();
int ret=0;
GmsOrderInst gmsOrderInst = null;
Configuration configuration =null;
String FlieNameA=fileToUpload.getOriginalFilename();
String FileNameB=UUID.randomUUID()+"-"+FlieNameA;
if(fileToUpload.getSize()==0){
map.put("isNull","请选择需要上传的技术文件!");
return map;
}
configuration = new Configuration();
configuration.setName("FileURL");
String FileURL = configurationService.queryConfiguration(configuration).get(0).getValue();
File file = new File(FileURL);
if(!file.exists()){
file.mkdirs();
}
try {
fileToUpload.transferTo(new File(FileURL,FileNameB));
} catch (IllegalStateException e) {
map.put("isExection","文件上传到服务器出现错误!");
return map;
} catch (IOException e) {
map.put("isExection","文件上传到服务器出现错误!");
return map;
}
GmsComments gmsComments = new GmsComments();
gmsComments.setCreateBy(request.getSession().getAttribute("accountName").toString());
gmsComments.setGgdId(GgdId);
gmsComments.setFilename(FileNameB);
try {
ret=gmsCommentsService.add(gmsComments);
} catch (Exception e) {
map.put("isExection","文件添加到数据库出现异常!");
return map;
}
gmsComments = null;
if(ret<=0){
map.put("error","文件添加到数据库操作出错!");
return map;
}else{
map.put("success","文件上传成功!");
return map;
}
}
三,注意事项。
options参数说明:
1、url 上传处理程序地址。
2,fileElementId 需要上传的文件域的ID,即<input type="file">的ID。是后台取值的标示如:@RequestParam("fileToUpload") MultipartFile fileToUpload
3,secureuri 是否启用安全提交,默认为false。
4,dataType 服务器返回的数据类型。可以为xml,script,json,html。如果不填写,jQuery会自动判断。
5,success 提交成功后自动执行的处理函数,参数data就是服务器返回的数据。
6,error 提交失败自动执行的处理函数。
7,data 自定义参数。这个东西比较有用,当有数据是与上传的图片相关的时候,这个东西就要用到了。
8, type 当要提交自定义参数时,这个参数要设置成post
错误提示:
1,SyntaxError: missing ; before statement错误
如果出现这个错误就需要检查url路径是否可以访问
2,SyntaxError: syntax error错误
如果出现这个错误就需要检查处理提交操作的服务器后台处理程序是否存在语法错误
3,SyntaxError: invalid property id错误
如果出现这个错误就需要检查文本域属性ID是否存在
4,SyntaxError: missing } in XML expression错误
如果出现这个错误就需要检查文件name是否一致或不存在
5,其它自定义错误
大家可使用变量$error直接打印的方法检查各参数是否正确,比起上面这些无效的错误提示还是方便很多。
四,源文件。
// JavaScript Document
jQuery.extend({
createUploadIframe: function(id, uri)
{
//create frame
var frameId = ‘jUploadFrame‘ + id;
if(window.ActiveXObject) {
var io = document.createElement(‘<iframe id="‘ + frameId + ‘" name="‘ + frameId + ‘" />‘);
if(typeof uri== ‘boolean‘){
io.src = ‘javascript:false‘;
}
else if(typeof uri== ‘string‘){
io.src = uri;
}
}
else {
var io = document.createElement(‘iframe‘);
io.id = frameId;
io.name = frameId;
}
io.style.position = ‘absolute‘;
io.style.top = ‘-1000px‘;
io.style.left = ‘-1000px‘;
document.body.appendChild(io);
return io;
},
createUploadForm: function(id, fileElementId)
{
//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);
//set attributes
jQuery(form).css(‘position‘, ‘absolute‘);
jQuery(form).css(‘top‘, ‘-1200px‘);
jQuery(form).css(‘left‘, ‘-1200px‘);
jQuery(form).appendTo(‘body‘);
return form;
},
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;
var form = jQuery.createUploadForm(id, s.fileElementId);
var io = jQuery.createUploadIframe(id, s.secureuri);
var frameId = ‘jUploadFrame‘ + id;
var formId = ‘jUploadForm‘ + id;
if( s.global && ! jQuery.active++ )
{
// Watch for a new set of requests
jQuery.event.trigger( "ajaxStart" );
}
var requestDone = false;
// Create the request object
var xml = {};
if( s.global )
{
jQuery.event.trigger("ajaxSend", [xml, s]);
}
var uploadCallback = function(isTimeout)
{
// Wait for a response to come back
var io = document.getElementById(frameId);
try
{
if(io.contentWindow)
{
xml.responseText = io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:null;
xml.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document;
}else if(io.contentDocument)
{
xml.responseText = io.contentDocument.document.body?io.contentDocument.document.body.innerHTML:null;
xml.responseXML = io.contentDocument.document.XMLDocument?io.contentDocument.document.XMLDocument:io.contentDocument.document;
}
}catch(e)
{
jQuery.handleError(s, xml, null, e);
}
if( xml || isTimeout == "timeout")
{
requestDone = true;
var status;
try {
status = isTimeout != "timeout" ? "success" : "error";
// Make sure that the request was successful or notmodified
if( status != "error" )
{
// process the data (runs the xml through httpData regardless of callback)
var data = jQuery.uploadHttpData( xml, s.dataType );
if( s.success )
{
// ifa local callback was specified, fire it and pass it the data
s.success( data, status );
};
if( s.global )
{
// Fire the global callback
jQuery.event.trigger( "ajaxSuccess", [xml, s] );
};
} else
{
jQuery.handleError(s, xml, status);
}
} catch(e)
{
status = "error";
jQuery.handleError(s, xml, status, e);
};
if( s.global )
{
// The request was completed
jQuery.event.trigger( "ajaxComplete", [xml, s] );
};
// Handle the global AJAX counter
if(s.global && ! --jQuery.active)
{
jQuery.event.trigger("ajaxStop");
};
if(s.complete)
{
s.complete(xml, status);
} ;
jQuery(io).unbind();
setTimeout(function()
{ try
{
jQuery(io).remove();
jQuery(form).remove();
} catch(e)
{
jQuery.handleError(s, xml, null, e);
}
}, 100);
xml = null;
};
}
// Timeout checker
if( s.timeout > 0 )
{
setTimeout(function(){
if( !requestDone )
{
// Check to see ifthe request is still happening
uploadCallback( "timeout" );
}
}, s.timeout);
}
try
{
var form = jQuery(‘#‘ + formId);
jQuery(form).attr(‘action‘, s.url);
jQuery(form).attr(‘method‘, ‘POST‘);
jQuery(form).attr(‘target‘, frameId);
if(form.encoding)
{
form.encoding = ‘multipart/form-data‘;
}
else
{
form.enctype = ‘multipart/form-data‘;
}
jQuery(form).submit();
} catch(e)
{
jQuery.handleError(s, xml, null, e);
}
if(window.attachEvent){
document.getElementById(frameId).attachEvent(‘onload‘, uploadCallback);
}
else{
document.getElementById(frameId).addEventListener(‘load‘, uploadCallback, false);
}
return {abort: function () {}};
},
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" )
{
eval( "data = " + data );
}
// evaluate scripts within html
if( type == "html" )
{
jQuery("<div>").html(data).evalScripts();
}
return data;
}
});
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。