About Ajaxfileupload.js Upload image usage history (STRUTS2)

Source: Internet
Author: User

Because to use the upload image function, attach the picture description information, and the traditional <s:file/> due to some limitations in this small module can not be used, so found the use of Ajaxfileupload.js plug-in upload method, in the course of use, JSP,JS, Struts2

Because I am not familiar with the Ajax situation has a lot of small problems, here to record, convenient to view, but also hope to help others,

First say the idea, by clicking Upload directly trigger JS function call Background to copy the image to the specified server directory, return the saved path to the foreground, and then follow the picture description information with Ajax asynchronous to the backstage. (PS: If there is a new method, please tell me, I will only this)

First, I'll put the JSP code on it,

<inputtype= "File"onchange= "Uploadimage (this)"ID= "Newsimgfile"name= "Tbslidefile" /><inputtype= "hidden"ID= "Imgpath"name= "Imgpath" /><Divclass= "Newlyhead">Title:</Div><Divclass= "Newlycontent"><inputtype= "text"class= "Upload_title"ID= "Slidetitle"name= "Slidetitle"></Div><inputtype= "button"value= "Save"onclick= "Savetwo ();"  >

Remember to add the necessary JS plugin, here I wrote the JS called Index.js

<script type= "Text/javascript" src= "Js/jquery.js" ></script>
<script type= "Text/javascript" src= "Js/ajaxfileupload.js" ></script>
<script type= "Text/javascript" src= "Js/index.js" ></script>

Here is the JS code I wrote myself

functionuploadimage (obj) {varFileelementid = "Newsimgfile"; Note here that Newsimgfile is the ID of the above input type= "file" If you need to modify remember to modify the $ ("#newsImgFile"). attr (' name ', ' file '); Obviously. attr is the setting of the attribute value of the element, of course, if you simply upload the picture can not be so troublesome, directly below the fileelementid:** attribute with input ID name consistent OK, through the conversion again, you can conveniently in JS for different picture control, Of course, there's no use to alert ("Test"); Just to see if it's done here, you can remove$.ajaxfileupload ({URL:' Uploadaction ',//need to link to server addressSecureuri:false, Fileelementid:fileelementid,//ID property of the File selection boxDataType: ' JSON ',//the format that the server returns can be otherSuccessfunction(Response, status, XHR) {//Post-Success callback functionConsole.log (response.obj); This method can be used in browser (chrome, etc.) to review elements of console console output//alert (response.obj);$ (' #imgPath '). Val (response.obj); This is for the above input id= "Imgpath" assignment, together to the background}, error:function(data, status, E) {//equivalent to the use of Catch statement blocks in Java$ (' #imgPath '). Val (' '); }        });}functionSavetwo () {$.ajax ({type:"POST", DataType:"Text", ContentType:"Application/x-www-form-urlencoded; Charset=utf-8 ", URL:"Addslide",//IS action because it uses the STRUTS2 framework data: {slidetitle:$ ("#slideTitle"). Val (), slidepath:$ ("#imgPath"). Val ()}, Success:function(response, status, XHR) {console.log (response);    Response is the value returned by alert (status); Status is state, such as successif(status== "Success") {Jalert ("Added successfully! "," Prompt Message "); }         Else{Jalert ("Add failed! "," Prompt Message "); }    } });}

Believe that the above on the JS description will be very clear, the next is the background code, simply receive the JS upload the picture and return to the path to the front JS

 Package*****ImportJava.io.File;ImportJava.io.FileInputStream;ImportJava.io.FileOutputStream;ImportJava.text.SimpleDateFormat;Importjava.util.Date;ImportJavax.servlet.http.HttpServletResponse;ImportNet.sf.json.JSONArray;ImportNet.sf.json.JSONObject;ImportOrg.apache.struts2.ServletActionContext;ImportCom.opensymphony.xwork2.ActionSupport;/** *@authore-Mail: *@versioncreate time:2014-6-16 Morning 10:43:43 *class introduce*/ Public classUploadactionextendsActionsupport {Privatefile file; PrivateString Filefilename; PrivateString Savepath; PrivateString obj; /*** Private variable file to and JS in $ ("#newsImgFile"). attr (' name ', ' file '); Consistent, so it can be directly accepted * Here is a simple picture uploaded to the server, this savepath is configured in Struts.xml The * **/@Override PublicString Execute ()throwsException {String Bigurl= ""; SimpleDateFormat SF=NewSimpleDateFormat ("Yyyymmddhhmmss"); Date Now=NewDate (); String Ddir=Sf.format (now); String Fext= Filefilename.substring (Filefilename.lastindexof ("."))); String Savepath= Servletactioncontext.getservletcontext (). Getrealpath ( This. Getsavepath ()); Bigurl= savepath+ "\ \" +ddir +Fext; Try{File F= This. GetFile (); FileInputStream InputStream=NewFileInputStream (f); FileOutputStream OutputStream=NewFileOutputStream (Bigurl); byte[] buf =New byte[1024]; intLength = 0;  while(length = Inputstream.read (BUF))! =-1) {outputstream.write (buf,0, length);            } inputstream.close ();            Outputstream.flush ();        Outputstream.close (); } Catch(Exception e) {e.printstacktrace (); }                //directly before the string can be received, if the same as the following comments converted to JSON before the conversion, I tried this can be directly in the front JS response get,Obj =bigurl.substring (bigurl.lastindexof ("Fileresources")) ; //System.out.println ("\" success\ ": True,\" url\ ": \" "+ddir+"/"+fext+" \ "\" bigurl\ ": \" "+bigurl+" \ "");//Jsonobject jsonobj = jsonobject.fromobject (path);//obj = jsonobj.tostring ();        returnSUCCESS; }     PublicFile GetFile () {returnfile; }     Public voidsetfile (file file) { This. File =file; }     PublicString Getfilefilename () {returnFilefilename; }     Public voidsetfilefilename (String filefilename) { This. Filefilename =Filefilename; }     PublicString Getsavepath () {returnSavepath; }     Public voidSetsavepath (String savepath) { This. Savepath =Savepath; }     PublicString getobj () {returnobj; }     Public voidsetobj (String obj) { This. obj =obj; }}

As for the image path and image title to the backstage, get and save, is fade out of the struts2 background processing, there is no need to post it out,

Configure this action in Struts.xml

<Actionname= "Uploadaction"class= "Com.gt.***.action." Uploadaction " >    <paramname= "Savepath">/fileresources/imagefile</param>    <resultname= "Success"type= "JSON">        <paramname= "ContentType">text/html</param>                </result></Action>

As for why Param is like this, I did not dig deep, if a friend knows trouble tell me, thank you.

Another ajaxfileupload.js plug-in is very good to get, Baidu you can haha.

 

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.