Springmvc+ajax Upload a picture (file) of the page with a Formdata object and immediately display it on the page

Source: Internet
Author: User
Tags button type port number server memory

Page form:

<form id= "Frm_identitya" action= "" enctype= "Multipart/form-data" >
	<span style= "Display:none" >
		<input type= "File" id= "Identitya" name= "Identitya" value= "" >
	</span>
	<input type= "hidden" Name= "mobile" value= "***********" >
</form>


Page picture labels and buttons:

<button type= "button" id= "Button_identitya" class= "btn btn-primary btn-lg btn-block" > Click Upload Image </button>

Page actions:

Click the button to select the picture
$ ("#button_identityA"). Click (function () {
	$ ("#identityA"). Click ();
});
When the input box changes, send the picture to the background
$ ("#identityA"). Change (function () {
	var formData = new FormData ($ ("#frm_identityA") [0 ]);
	$.ajax ({
		URL: "Userregeste/file/upload.do",//Configure the complete URL on demand, including IP and port number
		type: "POST",
		Data:formdata,
		Async:false,
		cache:false,
		contenttype:false,
		processdata:false,
		success:function ( Returndata) {
			alert ("Success");
			$ ("#img_identityA"). attr ("src", "userregeste/file/showimages.do?mobile=***********&name=identitya&" +new Date (). totimestring ());
			$ ("#img_identityA"). attr ("width", "124");
			$ ("#img_identityA"). attr ("height", "124")
		,
		error:function (returndata) {
			alert ("error");
			$ ("#img_identityA"). attr ("src", "app/images/icon011.png");
		}
	);}
);

Spring Configuration:

<!--picture Get maxuploadsize: Set maximum limit bytes to units---
<bean id= "Multipartresolver" class= " Org.springframework.web.multipart.commons.CommonsMultipartResolver ">
	<property name=" Maxuploadsize " Value= "1024000" ></property>
</bean>

The code in the action:
1, image upload

@Controller @RequestMapping ("/userregeste") public class Imageuploadaction {/** * store uploaded picture information */private static MAP
	
	<String,byte[]> images;
	static {images = new hashmap<string, byte[]> (); } @RequestMapping ("/file/upload") public Processresultmodel upload (httpservletrequest request,httpservletresponse Response) {//Get the file information from the request to the multiparthttpservletrequest type multiparthttpservletrequest mulrequest = Request Insta Nceof multiparthttpservletrequest?
		(multiparthttpservletrequest) Request:null;
		Request.getparameter ("mobile");//can still get from the request to the other than the picture parameters iterator<string> FileNames = Mulrequest.getfilenames (); if (Filenames.hasnext ()) {//Traversal request picture information in String filename = Filenames.next ();//Picture corresponding parameter name Log.debug ("fileName:" + fil
			ENAME); File = Mulrequest.getfile (fileName); Gets to the picture if (file! = null) {Log.debug ("file.getsize ():" + file.getsize ()); Picture size file.getbytes ();//Can get to the picture of the byte array Images.put (Filename,file.getbytes ());//GetTo the picture as an array of bytes saved in server memory}}}} 

2. Picture Display
The operation in the method after the AJAX request was sent successfully,
$ ("#img_identityA"). attr ("src", "userregeste/file/showimages.do?mobile=***********&name=identitya&" +new Date (). totimestring ());
It is worth mentioning that the SRC attribute in the IMG tag is for the UI staff to hold the static picture resource, but for programmers it should be known that the IMG tag actually sends a request based on the SRC attribute. At the same time, the browser will handle the SRC attribute of img If the SRC attribute value is not changed, only one request is sent, all plus the new Date (). toTimeString () to make each request different.
The code is as follows:

@RequestMapping ("/file/showimages") public
String showimages (httpservletrequest request,httpservletresponse Response) throws IOException {
	Log.debug ("Request Address:" +request.getrequesturi () + ", start getting Pictures");
	OutputStream sout = null;
	String mobile = Request.getparameter ("mobile");
	String name = Request.getparameter ("name"); Picture name
	Log.debug ("Mobile:" +mobile+ "	Name:" +name);
	if (mobile = = NULL | | name = NULL) {
		log.debug ("phone number or picture name is empty, getting picture failed. ");
		return null;
	}
	byte[] pictrue = null;
	Get the images picture from the local map
	pictrue = images.get (name);
	Log.debug ("Picture size:" +pictrue.length);
	try {
		if (pictrue! = null) {
			response.setcontenttype ("text/html");
			Sout = Response.getoutputstream ();
			Sout.write (pictrue);
			Sout.flush ();
			Sout.close ();
			Sout = null;
		} else {
			return null;
		}
	} catch (Exception e) {
		e.printstacktrace ();
	} finally {
		if (sout! = NULL) {
			sout.close ();
			Sout = null;
		}
	}
	Log.debug ("Return picture succeeded. ");
	return null;
}

This way, the picture will be displayed successfully on the page.

* Required JAR Package In addition to all SPRINGMVC jar packages,
Commons-fileupload-1.3.1.jar
Commons-io.jar
* After setting enctype= "Multipart/form-data", the form data is transmitted in binary form, Commons-fileupload-1.3.1.jar is to help us parse the binary data and encapsulate it into parameter, Do not add this package, from HttpServletRequest get parameters, you can get the binary stream data self-parsing.
* The above implementation of the dynamic transfer of images to the background, can be in the background to a series of images processing, high efficiency.

Page effect:


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.