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;
}
});

时间: 2024-08-03 13:34:55

ajaxfileupload.js 文件上传的相关文章

利用ajaxfileupload.js异步上传文件

1.引入ajaxfileupload.js 2.html代码 <input type="file" id="enclosure" name="enclosure"> <button id="upClick" >上传</button> 注意这里的input控件的id和name必须一致:这样在后台利用springMVC接受文件的时候能对应起来: 3.JS代码 <script type=&q

ajaxfileupload.js ajax上传文件(含application/json)

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(ty

ajaxFileUpload+springmvc文件上传例子

//文件上传页面 <div > <input type="file" id="file" name="file" onchange="ajaxFileUpload();"/> <input type="hidden" id="pic" name="pic" /> </div> //ajax 实现文件上传 function

Jquery form.js文件上传返回JSON数据,在IE下提示下载文件的解决办法,并对返回数据进行正确的解析

Jquery from.js插件上传文件非常方便,但是在ie10以下的版本会弹出下载文件对话框 解决方法: 1.在服务端设置response.setContentType("text/plain"); 2.对返回数据正确解析                这时返回的数据不再是json,不能使用解析json的方法进行解析                       var data1=eval("(" + data+ ")");  //将返回的字符

7款js文件上传插件

1.  jQuery File Upload 具有多文件上传.拖拽.进度条和图像预览功能的文件上传插件,支持跨域.分块.暂停恢复和客户端图像缩放.可与任何服务端平台(如PHP.Python.Ruby on Rails.Java.Node.js.Go等)一起使用,支持标准的HTML表单文件上传. 2.  Pixelcone Fileuploader 使用HTML5 API的jQuery文件上传插件,支持AJAX上传和拖拽操作,以及针对老版本浏览器的iframe上传部件.有多种形式来实现多文件上传,

JS文件上传神器bootstrap fileinput详解

Bootstrap FileInput插件功能如此强大,完全没有理由不去使用,但是国内很少能找到本插件完整的使用方法,于是本人去其官网翻译了一下英文说明文档放在这里供英文不好的同学勉强查阅.另外附上一段调用方发和servlet端的接收代码,未完待续. 引言: 一个强化的HTML5 文件输入插件,适用于Bootstrap 3.x.本插件对多种类型的文件提供文件预览,并且提供了多选等功能.本插件还提供给你一个简单的方式去安装一个先进的文件选择/上传控制版本去配合Bootstrap CSS3样式.通过

Node.js文件上传

Node.js express使用Multer实现文件上传html部分 <div> <h3>文件上传:</h3> 选择一个文件上传: <br/> <form action="/upload" method="post" enctype="multipart/form-data"> <input type="file" name="content&quo

使用ajaxfileupload.js异步上传文件到Servlet

前段时间帮同学做的毕业设计..好吧又是帮人做...需要上传文件,在这里使用了ajaxfileupload.js进行异步的上传文件到Servlet  ,后台保存了文件以后通过JSON返回文件路径到前端,好了废话不多说,直接上代码了... 前端页面比较简单 <input maxlength=16 type=file name="pic" id="pic" size=16 />  <input type="button" id=&qu

ajaxfileupload.js 异步上传文件

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%@ include file="/WEB-INF/views/include/taglib.jsp"%><%String path = request.getContextPath();String basePath = request.getScheme()