Ajax asynchronously uploads a picture file and converts it to the Base64 format

Source: Internet
Author: User
Tags base64

Advanced Browser, you can directly use the HTML5 FileReader, to obtain the base64 format of the uploaded file, and submitted as a string. For browsers below IE9, you'll have to think of other methods. The following is a sample code for the Advanced browser.

$ ('. Image '). Change (function(e) {vartarget =$ (e.target); varfile; if(Target[0].files && Target[0].files[0]) {file= Target[0].files[0]; }    if(file) {varReader =NewFileReader (); Reader.onload=function(evt) {varImgstr = Evt.target.result;//This is the Base64 string        };    Reader.readasdataurl (file);  }}); 

1. Ajax Upload Files Asynchronously

The Jquery.form plugin is used. The principle of the plugin is to create a hidden iframe that acts as a jump address for the IFRAME submission file. When you set the target property of a form to that IFRAME, the returned results are displayed in the IFRAME. This process can be implemented by itself or by using the jquery form plugin. The following code is with the help of plugins.
The HTML code is as follows. Added a button to commit a test, or to another trigger.

<formID= "Postform"Action= "uploadback.jsp"Method= "POST">  <ul>    <Li>        <span>Img:</span>        <inputID= "img"name= "img"type= "File"Accept= ". jpg">    </Li>    <Li>        <ahref= "javascript:void (0);">Submit</a>    </Li>  </ul></form>

The JS code is as follows. The success and failure methods can be defined on their own.

$ (' a '). Click (function() {    var options = {        ' json '),        success : GetResult,        error:showerror    }    $ (' #postForm '). Ajaxsubmit (options);});

2. Receive 2 images from the server
Reading the input stream directly from the server is not just a picture stream, but also a mixture of other information. If you get a picture stream, you need to remove the other information first. Here is the code that can output the captured picture stream locally and save it as a single picture.

ServletInputStream in =Request.getinputstream ();intresult; OutputStream out=NewFileOutputStream ("E:/test/2.jpg");byte[] buffer =New byte[1024];result= In.readline (buffer,0,buffer.length);//Read Boundaryresult = In.readline (buffer,0,buffer.length);//Read Content-dispositionresult = In.readline (buffer,0,buffer.length);//read Content-type;result = In.readline (buffer,0,buffer.length);//read empty lines;intLength =-1; while(length = in.read (buffer))! =-1) {out.write (buffer,0, length);} In.close (); Out.close ();

3. Convert 2 binary images to base64 format string
2 The binary stream is first deposited into the byte[] array, and then the Sun.misc.BASE64Encoder package is used to turn it. When the stream is stored in an array, it is not possible to read the complete data in the middle, so that the resulting string is not a complete picture, and then it is recycled to read to get a visual lossless image. In addition, the resulting base string, which may contain special symbols such as line breaks, is safe to handle. The code is as follows, and the variable is connected to the code.

Bytearrayoutputstream OutStream =NewBytearrayoutputstream ();byte[] Buff =New byte[100];//buff for storing temporary data that is read in a loopintrc = 0;  while(rc = in.read (buff, 0,)) > 0) {outstream.write (buff,0, RC); } byte[] data =Outstream.tobytearray (); In.close (); Base64encoder Encoder=NewSun.misc.BASE64Encoder (); String Base64str=encoder.encodebuffer (data). Trim (); Base64str= Base64str.replaceall ("[\\t\\n\\r]", "");

Summing up, feel the brain for a long time, is a little show tease, people are lazy, solve the problem of the cycle has become longer, and then have to move the brain diligent hands. In addition, Google is indeed more useful than Baidu.

Ajax asynchronously uploads a picture file and converts it to the Base64 format

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.