Java implementation Avatar Upload

Source: Internet
Author: User

Development environment: JDK1.7,MYECLIPSE10
The framework uses spring. Use the Maven tool (MAVEN's package Baidu can).

Four steps to complete, copy and change the parameters can be

First step: Limit the pictures in spring first
<!--Springmvc Upload a file, you need to configure the Multipartresolver processor--<BeanId="Multipartresolver"class="Org.springframework.web.multipart.commons.CommonsMultipartResolver" ><property name= "defaultEncoding" Span class= "Hljs-attribute" >value= "UTF-8"/> <!-- Specifies that the total size of the uploaded file cannot exceed 500KB. Note the limitations of the Maxuploadsize attribute are not for individual files, but for the sum of the capacity of all files. The size of this is in bytes, how big it is. Set--<property name=" maxuploadsize "value=" 500000 "/> <!--maximum memory size (10240)--<property name= "maxInMemorySize" value= "40960"/> </ BEAN>             

Step two: Write a JSP page
<%@ page language="Java" contenttype="Text/html; Charset=utf-8 "pageencoding="UTF-8"%><% @taglib prefix="C" uri="Http://java.sun.com/jsp/jstl/core"%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "HTTP://WWW.W3.ORG/TR/HTML4/LOOSE.DTD" ><Html><Head><ScriptType="Text/javascript"Src=".. /js/jquery-1.7.1.min.js "></Script><Metahttp-equiv="Content-type"Content="Text/html; Charset=utf-8 "><Title> Uploading Images</Title></Head><Body><Formaction="Filesupload"Method="POST"Name="Xiangmu"Id="Xiangmu"Enctype="Multipart/form-data" ><Table><Tr><Td> ID Image upload:</Td><Td><InputType=FileName="Myfiles"Id="Doc"Onchange="ShowImage ();" ></Td><DivId="Localimag" ><ImgId="Preview"Width=-1height=-1style="Diplay:none"/></Div></Tr><Tr><Td> operation of the company:</Td><!--to upload a picture, the name of the upload box is the same--<Td><InputType="File"Name="Myfiles"Id="Doc1" ></Td><Td></td> </ tr> <tr> <td>< Input type= "submit" value=< Span class= "Hljs-value" > "submit"/> </td> </tr> </ table> </form> </body></ HTML>             

Note:
Multi-image upload, the name of the upload box is the same, equal to send a multipartfile[] array.
Not only supports uploading images, but also supports multiple file uploads.
Form enctype= "Multipart/form-data", this is required to upload files.

Step three: If you want to implement the function of the page to show the picture, add the following method to the JSP page:
<ScriptType="Text/javascript" > functionShowImage() {var docobj = document.getElementById ("Doc");var Imgobjpreview = document.getElementById ("Preview");if (Docobj.files && docobj.files[0]) {Under Firefox, directly set the img attribute ImgObjPreview.style.display =' Block '; ImgObjPreview.style.width =' 300px '; ImgObjPreview.style.height =' 120px ';IMGOBJPREVIEW.SRC = Docobj.files[0].getasdataurl ();Firefox 7 or above can not be obtained using the above Getasdataurl () method, need a way imgobjpreview.src = window. Url.createobjecturl (docobj.files[0]); }else {ie, use the filter Docobj.select ();var imgsrc = Document.selection.createRange (). text;var localimagid = document.getElementById ("Localimag");//must set initial size LocalImagId.style.width =  "250px"; LocalImagId.style.height =  "200px"; //image exception capture, prevent users from modifying the suffix to forge the picture try {localImagId.style.filter = Span class= "hljs-string" > "Progid:DXImageTransform.Microsoft.AlphaImageLoader (Sizingmethod=scale)"; Localimagid.filters. Item ( "DXImageTransform.Microsoft.AlphaImageLoader"). src = imgsrc;} catch (e) {alert ( "Your uploaded picture is not in the correct format, please re-select!"); return false;} imgObjPreview.style.display =  ' none '; Document.selection.empty (); } return true;} </SCRIPT>         

Note: This method can only be uploaded to the display, unless you set multiple div. Or: Show multiple images to find other ways.

Fourth Step: Background receive
@RequestMapping ("/filesupload")Requestparam to write to know is the front desk of that arrayPublic String filesupload (@RequestParam ("Myfiles") multipartfile[] files, httpservletrequest request) {List<string>List =New Arraylist<string> ();if (Files! =Null && files.length >0) {for (int i =0; i < files.length; i++) {Multipartfile file = Files[i];Save FileList = SaveFile (request, file,list); } }Write the test, delete it and you canfor (int i =0; I <List.size (); i++) {System.out.println ("Data inside the collection" +List.get (i)); }Return"Index";Page to jump}PrivateList<string> SaveFile (httpservletrequest request, Multipartfile file,List<string>List) {Determine if the file is emptyif (!file.isempty ()) {try {//the saved file path (if using a TOMCAT server, the file is uploaded to \\%tomcat_home%\\ Webapps\\yourwebproject\\upload\\ folder //) String FilePath = Request.getsession (). Getservletcontext (). Getrealpath ( "upload/" + File.getoriginalfilename (); list.add (File.getoriginalfilename ()); File Savedir = new file (FilePath); if (!savedir.getparentfile (). exists ()) Savedir.getparentfile (). Mkdirs (); //dump file File.transferto (savedir); return list;} catch (exception e) {e.printstacktrace ();}} return list;}          

Note: Upload is a folder, you can create a new one and run it again to avoid errors.

The end, all replication can be achieved.

Java implementation Avatar Upload

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.