Ajax uploads files based on IFRAME

Source: Internet
Author: User

I found some methods for uploading Ajax files online. One method is to use JavaScript to read the file content of the client and encapsulate it in the HTTP protocol, it is then uploaded to the server, but I think this is not safe for users. So I checked some related books and found a file upload Method Based on the HTML tag <IFRAME> In the Ajax complete manual, I would like to summarize your hope to help you:

The general idea is to display the uploaded information in the IFRAME tag on the page, that is, set the target attribute of the form to the name value of IFRAME, in this way, the server information is fed back to the IFRAME on the page, enabling partial refresh upload.

The corresponding HTML source code is as follows:

<! Doctype HTML public "-// W3C // dtd xhtml 1.0 transitional // en" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <br/> <HTML xmlns = "http://www.w3.org/1999/xhtml"> <br/> <pead> <br/> <meta http-equiv = "Content-Type" content = "text/html; charset = UTF-8 "/> <br/> <title> pop-up form </title> <br/> </pead> </P> <p> <body style =" position: absolute; Z-index: 0; margin: 0; padding: 0; width: 100%; Height: 100%; "> <br/> <MCE: Script Type = "text/JavaScript"> <! -- <Br/> var windowstatus = false; <br/> // The unit "PX" is a string when the CSS Image value is obtained, conversion <br/> function getpxnumber (PX) <br/>{< br/> PX = px. replace ("PX", ""); <br/> return number (PX); <br/>}< br/> function showwindows () <br/>{</P> <p> var lockwindows = document. getelementbyid ("breakdiv"); <br/> var loginframe = document. getelementbyid ("login"); <br/> // obtain the width and height of the visible area of the page <br/> var 1_wwidth = (document. layers )? Window. innerwidth: Document. Body. clientwidth; <br/> var callback wheight = (document. layers )? Window. innerheight: Too Many Doc ument. body. clientheight; <br/> lockwindows. style. width = required wwidth; <br/> lockwindows. style. height = running wheight; <br/> // set the form to moderate <br/> loginframe. style. left = parseint (Fig-getpxnumber (loginframe. style. width) + document. body. scrollleft)/2) + document. body. scrollleft; <br/> loginframe. style. top = parseint (Fig-getpxnumber (loginframe. style. height)/2) + document. body. scro Lltop; <br/> lockwindows. style. display = "Block"; <br/> loginframe. style. display = "Block"; <br/> windowstatus = true; <br/>}< br/> function closewindows () <br/>{< br/> var lockwindows = document. getelementbyid ("breakdiv"); <br/> var loginframe = document. getelementbyid ("login"); <br/> lockwindows. style. display = "NONE"; <br/> loginframe. style. display = "NONE"; <br/> windowstatus = false; <br/>}</P> <p> window. onresize = func Tion () <br/>{< br/> If (windowstatus) <br/> showwindows (); <br/> }; </P> <p> // close the form after the upload is successful <br/> function uploadfile () <br/>{< br/> closewindows (); // close the form to display the returned information <br/>}< br/> // --> </MCE: SCRIPT> <br/> <! -- A div of the lock form --> <br/> <Div id = "breakdiv" style = "filter: alpha (opacity = 40); position: absolute; top: 0px; left: 0px; Z-index: 6; display: none; Background-color: #000; "> <br/> </div> <br/> <Div id =" login "<br/> style =" position: absolute; Z-index: 10; width: 271px; Height: 122px; text-align: center; Border: # 00c solid 1px; display: none; Background-color: # FFF; "> <br/> <Div id =" title "style =" font-family: '', ''; font-size: 18px; Background-color: # 03f; color: # FFF; width: 271px; Height: 25px; "> <br/> <Div style =" float: Left; width: 200px; font-family: verdana, Geneva, sans-serif; font-weight: bold; "> File Upload </div> <br/> <input type =" button "style =" color: # c00; Border: solid 1px #9c0; float: Right; width: 30px; Background-color: # 03f; "onclick =" closewindows (); "value =" X "/> <br/> </div> <br/> <Div id =" form "style =" width: 230px; padding-top: 20px; margin-top: 20px; margin: 0 auto; "> <br/> <form action =" http: // localhost: 8080/ajax/uploadimage. JSP "method =" Post "enctype =" multipart/form-Data "target =" uploadinfo "> <br/> <input type =" file "name =" uploadfile "/> <br/> <input type = "Submit" value = "Upload"/> <br/> <input type = "button" value =" cancel "onclick =" closewindows (); "/> <br/> </form> <br/> </div> </P> <p> <input type =" button "onclick =" showwindows (); "value =" click "/> <br/> <IFRAME name =" uploadinfo "scrolling =" no "width =" 100% "Height =" 20% "frameborder =" 0 "onLoad = "uploadfile (); "> <br/> </iframe> <br/> </body> <br/> </ptml>

The corresponding Server Upload processing is processed using the servlet in JSP. The source code is as follows:

Package servlet; </P> <p> Import javax. servlet. *; <br/> Import javax. servlet. HTTP. *; <br/> Import Java. io. *; </P> <p> public class imguploadservlet extends httpservlet <br/> {<br/> // encode Chinese characters <br/> Public String codetostring (string Str) <br/>{< br/> try <br/> {<br/> byte [] Buf = Str. getbytes ("ISO-8859-1"); <br/> return new string (BUF); <br/>}< br/> catch (exception E) <br/>{< br/> E. printstacktrace (); <br/>}< br/> return NULL; <br/>}</P> <p> Public void dopost (httpservletrequest request, httpservletresponse response) <br/> throws servletexception, ioexception <br/>{< br/> request. setcharacterencoding ("UTF-8"); <br/> string tempfilepath = getservletcontext (). getrealpath ("/") + "/tempfile. TMP "; <br/> string tempfilename = new string (tempfilepath); <br/> file tempfile = new file (tempfilename); <br/> If (! Tempfile. exists () <br/> tempfile. createnewfile (); </P> <p> byte [] Buf = new byte [1000]; <br/> fileoutputstream writer = new fileoutputstream (tempfile ); <br/> // get the stream submitted by the user <br/> inputstream filesource = request. getinputstream (); <br/> // write the stream submitted by the user to a temporary file <br/> int N; <br/> while (n = filesource. read (BUF ))! =-1) <br/> writer. write (BUF, 0, n); <br/> filesource. close (); <br/> writer. close (); </P> <p> // parse the file content, in read-only mode <br/> randomaccessfile randaccessfile = new randomaccessfile (tempfile, "R "); <br/> // the first line of the file to be read, which is a separator <br/> randaccessfile. readline (); <br/> // read the second row of data. This row contains the file name and path information of the uploaded file on the client. <br/> string fileinfo = randaccessfile. readline (); <br/> // process the file name and encode the file. <br/> int Index = fileinfo. lastindexof ('//'); <br/> string Filename = codetostring (fileinfo. substring (index + 1, fileinfo. length ()-1); </P> <p> // locate the file pointer to the beginning of the file <br/> randaccessfile. seek (0); <br/> // get the location of the 4th line carriage return, which is the start position of the uploaded file's actual content <br/> int forth = 1; <br/> long forthentherposition = 0; <br/> while (n = randaccessfile. readbyte ())! =-1 & (forth <= 4) <br/> If (n = '/N') <br/>{< br/> forthentherposition = randaccessfile. getfilepointer (); <br/> forth ++; <br/>}</P> <p> // returns the position of the last 3rd carriage return characters, is the end position of the uploaded file content <br/> randaccessfile. seek (randaccessfile. length (); <br/> long endposition = randaccessfile. getfilepointer (); <br/> Int J = 1; <br/> while (endposition >=0 & (j <= 3 )) <br/>{< br/> endposition --; <br/> randaccessfile. seek (endposition); <br/> If (randaccessfi Le. readbyte () = '/N') <br/> J ++; <br/>}</P> <p> // Save the parsed content of the uploaded file <br/> string savepath = getservletcontext (). getrealpath ("/") + "/" + filename; <br/> file SaveFile = new file (savepath); <br/> If (! SaveFile. exists () <br/> SaveFile. createnewfile (); <br/> randomaccessfile writerfile = new randomaccessfile (SaveFile, "RW"); </P> <p> randaccessfile. seek (forthentherposition); <br/> long startpoint = randaccessfile. getfilepointer (); <br/> while (startpoint <endposition) <br/>{< br/> writerfile. write (randaccessfile. readbyte (); <br/> startpoint = randaccessfile. getfilepointer (); <br/>}< br/> writerfile. close (); <br/> Randaccessfile. close (); <br/> tempfile. delete (); // delete a temporary file </P> <p> response. setheader ("cache-control", "No-Cache"); <br/> response. setheader ("Pragma", "On-Cache"); <br/> response. setcontenttype ("HTTP/1.1 204 NO content/n"); <br/> response. setcontenttype ("text/html; charset = UTF-8"); </P> <p> printwriter out = response. getwriter (); </P> <p> out. println (filename + "uploaded successfully! "); <Br/>}< br/>}

Here we get the stream of the user's upload request, and the directly obtained stream also contains some information in the HTTP protocol. The form of temporary files that I get in this process is as follows:

----------------------------- 7db2ee1b100318 <br/> content-Disposition: Form-data; name = "file name without a suffix"; filename = "file absolute file name (including path) on the client) "<br/> Content-Type: MIME type </P> <p>" file content "<br/> --------------------------------- 7db2ee1b100318 -- <br/>

Therefore, it is necessary to obtain the truly uploaded file content after processing.

If you want to know more about the HTTP protocol interaction process, we recommend that you use the httpwatch tool to record the HTTP protocol sent and received by the browser, which is very convenient for Ajax learning!

If you have any questions in the above article, please criticize and point out!

 

Related Article

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.