Ajaxfileupload.js File Upload

Source: Internet
Author: User
Tags new set

One, foreground code.

<input id= "filetoupload" type= "file" size= "" Name= "filetoupload" class= "Input" >
<button class= "button" id= "Buttonupload" onclick= "return Ajaxfileupload ();" > Upload Technical Documents </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 ("Technical file Upload", data.isnull);
Return
}

if (data.isexection! = NULL && data.isexection! = ") {
Parent.$.messager.alert ("Technical file Upload", data.isexection);
Return
}

if (data.error! = NULL && Data.error! = ") {
Parent.$.messager.alert ("Technical file Upload", data.error);
Return
}

if (data.success! = NULL && data.success! = ") {
Parent.$.messager.progress ({
Title: "Technical File Upload",
Msg:data.success
});
SetTimeout (function () {
Parent.$.messager.progress (' close ');
},1500);

}

},
Error:function (data, status, E) {
Alert (e);
}
}
);

},
Error:function () {alert ("error");}
});

return false;

};

Two, backstage code.

@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", "Please select a technical file to upload!");

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", "File upload to server Error!");
return map;
} catch (IOException e) {
Map.put ("Isexection", "File upload to server Error!");
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", "file added to database exception!");
return map;
}

Gmscomments = null;


if (ret<=0) {
Map.put ("Error", "file added to database operation Error!");
return map;
}else{
Map.put ("Success", "File Upload succeeded!");
return map;
}

}

Three, the attention matters.

Options parameter Description:

1, URL upload handler address.
2,fileelementid the ID of the file domain that needs to be uploaded, which is the ID of <input type= "file" >. is the background value of the indicator such as: @RequestParam ("Filetoupload") Multipartfile filetoupload
3,secureuri whether secure commits are enabled, false by default.
4,datatype the data type returned by the server. Can be a xml,script,json,html. If you do not fill in, jquery will automatically determine.
5,success the processing function that is executed automatically after the commit succeeds, the parameter data is the server return.
6,error the processing function that failed to submit the automatic execution.
7,data custom parameters. This thing is more useful, when the data is related to the uploaded image, this thing will be used.
8, type when you want to submit a custom parameter, this parameter is set to post

Error message:

1,syntaxerror:missing; Before statement error
If this error occurs, you will need to check if the URL path is accessible
2,syntaxerror:syntax Error errors
If this error occurs, you need to check the server spooler that handles the commit operation for any syntax errors
3,syntaxerror:invalid Property ID Error
If this error occurs, you need to check whether the Text field property ID exists
4,syntaxerror:missing} in XML expression error
If this error occurs, you need to check whether the file name is consistent or not present.
5, other custom errors
You can use the variable $error Direct printing method to check whether the parameters are correct, compared to the above these invalid error prompts are much more convenient.

Four, source files.

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

Ajaxfileupload.js File Upload

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.