Amoy Mall Series--to achieve the image upload function

Source: Internet
Author: User

http://blog.csdn.net/yerenyuan_pku/article/details/72808000

Above we use fastdfs-client to carry on the simple file upload operation test, the function that uploads the picture when adding the item in Amoy Mall item is not realized, as shown in. This article will spend a lot of ink to teach you how to achieve the image upload function.

We look at the item-add.jsp page, you can see the upload image triggered by the method is called Picfileupload class to deal with, under <a> the label is a hidden field, is used to receive images uploaded to the image server's echo address, When we submit the form, we can save the image address in the database.

The picture upload process is like this, after the item-add.jsp page is loaded, the taotao.init is automatically called for initialization, as shown in.

Taotao is defined in the Common.js file, and we look at Common.js, and we can see that TAOTAO=TT is defined here, which this.initPicUpload(data); is used to initialize the upload component in the Init method. Initializing the upload component is the class that we defined in the item-add.jsp page called Picfileupload, because the upload operation may be called more than one place, so it is $(".picFileUpload").each(function(i,e){ used to initialize all the pages that call the upload component. If you have uploaded a picture and are now in the editing state, then use it _ele.siblings(".pics").find("ul").append("...") to load the previously added image. Click the upload image button, will load Rich text editing upload image interface, Rich text editor parameters are in the above var TT = TAOTAO = { , specify the name of the upload file parameters, the requested URL is/pic/upload, upload type is image, Flash, media, file four kinds.

Let's implement the image upload feature below.

Implement image upload function Guide package

Uploading images depends on the Commons-io and Commons-fileupload development packages, and we need to see if there are two jar packages in the Maven dependency of the Taotao-manger-web project. Currently there is Commons-io-1.3.2.jar this jar package (it is in the Maven dependency of the Taotao-common project, and Taotao-manager-web relies on Taotao-common, so it also has this jar package), But there is no commons-fileupload, so we need to add a dependency on commons-fileupload in the Pom.xml file of the Taotao-manager-web project. &NBSP,
 
adds the following dependencies, because the version number is defined uniformly in the Taotao-parent project, so there is no need to specify a version number here.

<!-- 文件上传组件 --><dependency>    <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId></dependency>
Config file Upload parser

We need to configure the file upload parser in the Springmvc.xml file of the Taotao-manager-web project, as shown in.

For the convenience of replication, the file Upload parser configuration is now posted:

<!--definition File upload parser--<BeanId="Multipartresolver"class="Org.springframework.web.multipart.commons.CommonsMultipartResolver" > <!--Set default encoding-- < Property name="defaultencoding" value="UTF-8" ></property> <!-- Set the maximum file upload value 5mb,5*1024*1024- <property name="maxuploadsize" value="5242880" ></property></bean>         
    • 1
Configure Access Picture prefixes

We access the images as HTTP, for example http://192.168.25.133/group1/M00/00/00/wKicDVjxPn2AOBiGAAHk-VzqZ6w952.jpg , from the above we know that the image server returned image path is, that is, group1/M00/00/00/wKicDVjxPn2AOBiGAAHk-VzqZ6w952.jpg there is no previous part of the path, that is http://192.168.25.133/ , and we can not write dead prefixes in the code, because the IP and port numbers are likely to change, So it is best to put in the configuration file, we create a new resource.properties file in the Src/main/resources/resource directory, the configuration file input IMAGE_SERVER_URL=http://192.168.25.133/ , This indicates that the access port of the Nginx configuration in the image server is the default port of 80, as shown in.

Load configuration file

After we have created the Resource.properties file above, we need to load the configuration file in the spring container, so we add the following configuration in the Springmvc.xml configuration file:

<context:property-placeholder location="classpath:resource/resource.properties" />
    • 1
    • 1

As shown in the following:

As a result, the complete contents of the Springmvc.xml configuration file are as follows.

<?xml version= "1.0" encoding= "UTF-8"?><Beansxmlns="Http://www.springframework.org/schema/beans"Xmlns:xsi="Http://www.w3.org/2001/XMLSchema-instance"xmlns:p="Http://www.springframework.org/schema/p"xmlns:context="Http://www.springframework.org/schema/context"xmlns:dubbo="Http://code.alibabatech.com/schema/dubbo"Xmlns:mvc="Http://www.springframework.org/schema/mvc"xsi:schemalocation="Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/MVC http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd/HTTP Code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd/HTTP Www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd " ><!--load Properties file--<Context:property-placeholderlocation="Classpath:resource/resource.properties"/><Context:component-scanBase-package="Com.taotao.controller"/><Mvc:annotation-driven/><Beanclass="Org.springframework.web.servlet.view.InternalResourceViewResolver" ><PropertyName="prefix"Value="/web-inf/jsp/"/><PropertyName="Suffix"Value=". jsp"/></Bean><!--static resource mapping--<Mvc:resourceslocation="/web-inf/js/"mapping="/js/**"/><Mvc:resourceslocation="/web-inf/css/"mapping="/css/**"/><!--definition File upload parser--<BeanId="Multipartresolver"class="Org.springframework.web.multipart.commons.CommonsMultipartResolver" ><!--Set default encoding--<PropertyName="Defaultencoding"Value="UTF-8" ></Property><!--set the maximum file upload value 5mb,5*1024*1024--<PropertyName="Maxuploadsize"Value="5242880" ></Property></Bean><!--reference Dubbo Services--<Dubbo:applicationName= "Taotao-manager-web"/> <dubbo: Registry protocol= "zookeeper" address= "192.168.25.128:2181"/> <dubbo:reference interface=< Span class= "Hljs-value" > "Com.taotao.service.ItemService" id=  "Itemservice"/> <dubbo:reference interface= "Com.taotao.service.ItemCatService" id= "Itemcatservice"/></ BEANS>             
    • 1
Create a Controller

We need to create a new Picturecontroller class to handle the image upload operation, as shown in.

In @Value("${IMAGE_SERVER_URL}") order to inject the picture access prefix that we configured in the configuration file resource.properties. @RequestMapping("/pic/upload")Specifies the URL of the upload file (picture) request, as with the specified URL, the parameter--uploadfile in the Uploadpic method is the same as the argument name of the uploaded file.

So the method Uploadpic should return what format, we can see from the Kindeditor official website, as shown, we can see that the return value format is a JSON string, then we have three ways to implement. The first is to directly return the data in the map format, both JSON and map data are in the form of key and value, so it is no problem to return to map. The second is to create a Pojo class that has three properties, error, URL, message, and then returns after the class is converted to JSON. The third is to turn the map into a JSON string return. Here we use the first method for the moment.

In order to facilitate everyone to copy, now the Picturecontroller class code paste as follows:

/** * Image Upload Controller * <p>Title:PictureController</p> * <p>description: </p> * <p>company : Www.itcast.cn</p> *@version 1.0 */@ControllerPublicClassPicturecontroller {@Value ("${image_server_url}")Private String Image_server_url;@RequestMapping ("/pic/upload")@ResponseBodyPublic MapUploadpic (Multipartfile uploadfile) {try {First receive the page upload filebyte[] content = Uploadfile.getbytes ();Remove file extension String originalfilename = Uploadfile.getoriginalfilename (); String ext = originalfilename.substring (Originalfilename.lastindexof (".") +1);Upload the contents of this file to the image server Fastdfsclient fastdfsclient =new fastdfsclient ( "classpath:resource/fast_dfs.conf"); String url = fastdfsclient.uploadfile (content, ext); //take the URL of the image server from the configuration file //Create a return result object Map result = new HashMap (); Result.put ( "error", 0); Result.put (  "url", Image_server_url + URL); //return results return result;} catch (Exception e) {e.printstacktrace (); Map result = new HashMap () result.put ( "error", 1); Result.put ( "message",  "picture upload failed"); return result; }} 
    • 1
Test image upload function

After we are all configured, now we will try the image upload function, as shown, found that click "Start upload" after the picture normal echo.

Then we click on the "Insert All" button, you can see the "Upload image" button below the four images we just uploaded, we can click on any of the images in the browser browsing, such as we click on the third image--a.jpg.

The effect that is accessed in the browser is as shown in. This will enable our image upload function.

(turn) Amoy Mall Series--to achieve the image upload function

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.