Detailed react, Ajax, Java implementation upload image and preview function

Source: Internet
Author: User
React+ajax+java How do I upload images and preview them? This article will share with you react, Ajax, Java implementation upload images and preview features, with a certain reference value, interested in small partners can refer to, hope to help everyone.

Before the internet to find Ajax upload pictures of the data, most people write is using jquery, but here with jquery on the big only small use, so I wrote it myself, first.

By, first click on the above selection file, after selecting the picture, will automatically upload the picture to the server, and return the picture name and picture on the server path, then display the file name and picture on the page.

SOURCE :Ajax upload Preview

In react:


Import React from ' React ', import Http from './http ' const URL = ' Http://localhost:8080/fileuploadExample/UploadServlet ';    Export default class App extends React.component {constructor (props) {super (props);  This.state = {uploadedfile: "", Uploadedfilegeturl: '}; } error () {alert (' ERROR ')} callback (Result) {this.setstate ({uploadedFile:result.uploadedFile, Uplo  ADEDFILEGETURL:RESULT.UPLOADEDFILEGETURL}); } handleimageupload (e) {e.preventdefault () let file = E.target http.post (URL, file, This.callback.bind (this), T His.error)} render () {return (<p> <input type= "file" onchange={this.handleimageupload.bind (th IS)}/> <p> {this.state.uploadedFileGetUrl = = = '? Null: <p> <p            >{this.state.uploadedFile}</p>  </p>} </p> </p>) }} 

Self-encapsulated AJAX code:


var http = (function () {var http = {}; if (typeof window. XMLHttpRequest = = = "undefined") {window. XMLHttpRequest = function () {//If i5 is used with Microsoft, the other uses MSXML2 return to new window. ActiveXObject (navigator.useragent. IndexOf ("MSIE 5") >= 0?    "Microsoft.XMLHTTP": "Msxml2.xmlhttp");  }; } http.post = function (URL, data, callback, error) {if (typeof data = = = "function") {//data can not wear value callback = data      ;    data = null;    } var timeout = setTimeout (function () {//Timeout setting error ();    }, 10000);    var xhr = new XMLHttpRequest ();    Xhr.open (' post ', url); Xhr.onreadystatechange = function () {if (xhr.readystate = = = 4) {cleartimeout (timeout);//Clear Timeout if (xhr.          Status = = =) {//alert (xhr.responsetext);        Callback (Json.parse (Xhr.responsetext));//Call callback function} else {error ();    } xhr = null;//Delete object to prevent memory overflow}};     Xhr.onerror = function () {//If error cleartimeout (timeout) is generated; Error ();    };  Xhr.send (Http.formdatacode (data));  };    Http.formdatacode = function (data) {var fd = new FormData ();    if (!data) {return null;        } for (var key in data) {if (data.files) {var file=data.files[0];      Fd.append ("image", file);      }else{fd.append (Key, Data[key]);  }} return FD; } return http;}) (); Export default Http

In the background of Java upload Pictures, there are many examples on the internet can be used, I borrowed from the http://blog.csdn.net/thc1987/article/details/15341201 this article, is interested to see:


Package Com.example;import Java.io.file;import Java.io.ioexception;import java.io.printwriter;import java.util.Date ; Import Java.util.list;import Javax.servlet.servletconfig;import Javax.servlet.servletcontext;import Javax.servlet.servletexception;import Javax.servlet.annotation.webservlet;import Javax.servlet.http.HttpServlet; Import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;import Net.sf.json.jsonobject;import Org.apache.commons.fileupload.fileitem;import Org.apache.commons.fileupload.disk.diskfileitemfactory;import org.apache.commons.fileupload.servlet.servletfileupload;/** * Servlet Implementation class Uploadservlet */@  Webservlet ("/uploadservlet") public class Uploadservlet extends HttpServlet {private static final long Serialversionuid =  1L;  The directory where the file is saved private static String Path_folder = "/";  The directory where temporary files are stored private static String Temp_folder = "/";    /** * @see httpservlet#httpservlet () */public Uploadservlet () {super (); ToDo auto-generated constructor stubs} @Override public void init (ServletConfig config) throws servletexception {//T    ODO auto-generated Method Stub super.init ();    ServletContext servletctx = Config.getservletcontext ();    Initialize path//save file directory Path_folder = Servletctx.getrealpath ("/upload");  The directory where the temporary files are stored, the directory where the xxx.tmp files are stored temp_folder = Servletctx.getrealpath ("/uploadtemp"); }/** * @see httpservlet#doget (httpservletrequest request, HttpServletResponse * response) */protected void DoG ET (httpservletrequest request, httpservletresponse response) throws Servletexception, IOException {response.sethe    Ader ("Access-control-allow-origin", "http://localhost:3000");    Response.setheader ("Access-control-allow-credentials", "true"); Request.setcharacterencoding ("Utf-8");    Set the encoding response.setcharacterencoding ("Utf-8");    Response.setcontenttype ("Text/html;charset=utf-8"); Get Disk File entry Factory Diskfileitemfactory factory = new Diskfileitemfactory ();   If you do not have the following two lines set, upload a large file will occupy a lot of memory,//Set up a temporary storage room, this storage room can be different from the final directory to store files/** * Principle it is to save to the temporary storage room, and then in the actual write to the corresponding directory of the hard disk    , in fact, when uploading a file, actually uploaded two copies, the first one is in. tem * format and then write it to the corresponding directory of the hard disk */factory.setrepository (new file (Temp_folder));    Sets the size of the cache, which is placed directly into the temporary storage room factory.setsizethreshold (1024 * 1024) when the capacity of the uploaded file exceeds the cache;    High level of API File upload processing servletfileupload upload = new Servletfileupload (factory); The try {//submit information is in this List//This means that multiple files can be uploaded//Please organize your own code list<fileitem> List = Upload.parserequest (      request);      Gets the uploaded file Fileitem item = getuploadfileitem (list);      Gets the file name String filename = getuploadfilename (item);      The saved file name is String savename = new Date (). GetTime () + filename.substring (Filename.lastindexof (".")); Browser access path after save picture String Picurl = request.getscheme () + "://" + request.getservername () + ":" + Request.getse      Rverport () + request.getcontextpath () + "/upload/" + savename; System.out. println ("Storage directory:" + Path_folder);      SYSTEM.OUT.PRINTLN ("FileName:" + filename);      SYSTEM.OUT.PRINTLN ("Browser access path:" + Picurl); Really write to disk item.write (new File (Path_folder, savename));      Third party provided by printwriter writer = Response.getwriter ();      System.out.print ("{");      System.out.print ("UploadedFile:" + "\" "+ filename +" \ ");      System.out.print (", uploadedfilegeturl:\" "+ Picurl +" \ "");            System.out.print ("}");      Jsonobject result = new Jsonobject ();      Result.put ("UploadedFile", filename);      Result.put ("Uploadedfilegeturl", Picurl);      Writer.write (Result.tostring ());    Writer.close ();      } catch (Exception e) {e.printstacktrace (); /* * PrintWriter writer = Response.getwriter ();       Writer.print ("{"); * Writer.print ("Error:" +e.tostring ());       Writer.print ("}");       * Writer.close (); */}} private Fileitem Getuploadfileitem (list<fileitem> List) {for (Fileitem fileitem:list) {if (! Fileitem.isformfield ()) {return fileitem;  }} return null;    } private String Getuploadfilename (Fileitem Item) {//Get path name string value = Item.getname ();    System.out.println (Value + ": Value");    Index to the last backslash int start = Value.lastindexof ("/");    Intercept the string name of the uploaded file, plus 1 to remove the backslash, string filename = value.substring (start + 1);  return filename; }/** * @see httpservlet#dopost (httpservletrequest request, HttpServletResponse * response) */protected void do Post (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException {doget (reques  T, response); }}

The above Java code modifies these points here:

1. Insert


Response.setheader ("Access-control-allow-origin", "http://localhost:3000"); Response.setheader (" Access-control-allow-credentials "," true ");

These two lines of code, which are cross-domain, of course, this may not be safe

2.


Jsonobject result = new Jsonobject (), Result.put ("UploadedFile", filename), result.put ("Uploadedfilegeturl", Picurl); Writer.write (Result.tostring ());

Here, the JSON data transfer between the page and the server is used

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.