React + ajax + java allows you to upload images and preview images.

Source: Internet
Author: User
Tags tmp file

React + ajax + java allows you to upload images and preview images.

In the past, I used ajax to upload images on the Internet. Most people wrote jQuery, but JQuery was used here, so I wrote it myself first.

First, click the selected file above. After selecting an image, the image will be automatically uploaded to the server and the image name and path will be returned on the server, the file name and image are displayed on the page.

Source code: 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, uploadedFileGetUrl: result. uploadedFileGetUrl});} handleImageUpload (e) {e. preventDefault () let file = e.tar get Http. post (URL, file, this. callback. bind (t His), this. error)} render () {return (<div> <input type = "file" onChange = {this. handleImageUpload. bind (this)}/> <div> {this. state. uploadedFileGetUrl = ''? Null: <div> <p> {this. state. uploadedFile} </p>  </div >}</div> </div> )}}

Self-encapsulated Ajax code:

Var Http = (function () {var http = {}; if (typeof window. XMLHttpRequest = "undefined") {window. XMLHttpRequest = function () {// Microsoft is used for i5, and Msxml2 return new window is used for others. activeXObject (navigator. userAgent. indexOf ("MSIE 5")> = 0? "Microsoft. XMLHTTP ":" Msxml2.XMLHTTP ") ;};} http. post = function (url, data, callback, error) {if (typeof data = "function") {// data can be left blank with 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. stat Us === 200) {// alert (xhr. responseText); callback (JSON. parse (xhr. responseText); // call the callback function} else {error () ;}xhr = null; // Delete the object to prevent memory overflow}; xhr. onerror = function () {// if the error clearTimeout (timeout); 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

Many examples of uploading images in the java background can be used on the Internet. For more information, see http://blog.csdn.net/thc1987/article/details/15341201:

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; // private static String PATH_FOLDER = "/"; // private static String TEMP_FOLDER = "/"; /*** @ see HttpServlet # HttpServlet () */public UploadServlet () {super (); // TODO Auto-generated constructor stub} @ Override public void init (ServletConfig config) throws ServletException {// TODO Auto-generated method stub super. init (); ServletContext servletCtx = config. getServletContext (); // initialization path // directory for saving files PATH_FOLDER = servletCtx. getRealPath ("/upload"); // directory for storing temporary files, storing xxx. directory of the tmp file: TEMP_FOLDER = servletCtx. getRealPath ("/uploadTemp");}/*** @ see HttpServlet # doGet (HttpServletRequest request, HttpServletResponse * response) */protected void doGet (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {response. setHeader ("Access-Control-Allow-Origin "," http://localhost:3000 "); Response. setHeader ("Access-Control-Allow-Credentials", "true"); request. setCharacterEncoding ("UTF-8"); // sets the encoding response. setCharacterEncoding ("UTF-8"); response. setContentType ("text/html; charset = UTF-8"); // Get disk file entries factory DiskFileItemFactory factory = new DiskFileItemFactory (); // if the following two rows are not set, uploading large files will occupy a lot of memory. // you can set a storage room for temporary storage, it may be different from the directory of the final stored file. * It stores the file in the temporary storage room first, and then uploads a file to the hard disk of the corresponding directory. In fact, two copies are uploaded, and the first one is. tem * Format and then write it to the hard disk of the corresponding directory */factory. setRepository (new File (TEMP_FOLDER); // sets the cache size. When the size of the uploaded File exceeds the cache, it is directly placed in the temporary storage room factory. setSizeThreshold (1024*1024); // high-level API File upload processing ServletFileUpload upload = new ServletFileUpload (factory ); try {// the submitted information is in this list. // This means that multiple files can be uploaded. // organize the code List <FileItem> list = upload. parseRequest (request); // get the uploaded file FileItem item = getUploadFileItem (List); // get the file name String filename = getUploadFileName (item); // save the file name String saveName = new Date (). getTime () + filename. substring (filename. lastIndexOf (". "); // the browser access path of the saved image String picUrl = request. getScheme () + ": //" + request. getServerName () + ":" + request. getServerPort () + request. getContextPath () + "/upload/" + saveName; System. out. println ("storage directory:" + PATH_FOLDER); System. out. println ("file name:" + Filename); System. out. println ("browser access path:" + picUrl); // The file is actually written to the disk item. write (new File (PATH_FOLDER, saveName); // third-party 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) {// obtain the path name String value = item. getName (); System. out. println (value + ": value"); // index to the last backslash int start = value. lastIndexOf ("/"); // specifies the String name of the uploaded file. Add 1 to remove the backslash and String filename = value. substring (start + 1); return filename;}/*** @ see HttpServlet # doPost (HttpServletRequest request, HttpServletResponse * response) */protected void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doGet (request, response );}}

The above java code is modified here:

1. Insert

response.setHeader("Access-Control-Allow-Origin","http://localhost:3000");response.setHeader("Access-Control-Allow-Credentials", "true");

These two lines of code are cross-origin. 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 page and server use json Data Transmission

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

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.