Image upload--jersey for restful interfaces

Source: Internet
Author: User
Tags json

The last time I used springmvc to upload pictures, this is the client to upload pictures and other fields together and then work together. (There is no harm to the temporary also did not think of) in short this time the hope can be stored in the image of the service independent, temporarily with Jersey implementation of an interface (the boss said that according to the truth should be used webservice to achieve, but I do not think there is any difference between the two AH =. =), and then submit the picture to the Jersey interface in SPRINGMVC to complete the storage.

This is a stand-alone picture. Storage Project Structure

Only one absolute path and one virtual path have been added to the config configuration file

<config>
<root>D:\\recommend\\images\\</root>
<uriroot>/static/image/ Recommendation/</uriroot></config>

The Springcontext.xml configuration file will need to be injected into a good

<context:component-scan base-package= "Com.xxx.upload" >

Register the necessary classes in the Restfulapplication.java

    Public restfulapplication () {
        register (requestcontextfilter.class);
        Add additional features such as support for Multipart.
        Register (multipartfeature.class);
        Load  Resource
        Register (recommendationpictureresource.class);
    }

Recommendationpictureresource.java

Private final Log logger = Logfactory.getlog (Recommendationpictureresource.class);
@Autowired @Qualifier ("Pictureservice") Pictureservice pictureservice;//the service class that stores the image @Autowired @Qualifier ("Xmlutils") An XML file parsing tool class for the Xmlutils xmlutils;//package org.apache.commons.configuration.XMLConfiguration to read the config configuration file @POST @ Path ("/upload") @Produces ("Application/json;charset=utf-8") @Consumes (mediatype.multipart_form_data) public String Loadpic (@FormDataParam ("type") string type, @FormDataParam ("ResourceId") string resourceId, @Form Dataparam ("file") InputStream FileInputStream, @FormDataParam ("file") Formdatacontentdisposition Contentdispositio
    Nheader) {Objectnode result = new Objectmapper (). Createobjectnode ();
        if (Type==null | | resourceId = = NULL | | fileinputstream = = NULL) {result.put ("Ret_code", 10001);
        Result.put ("ret_msg", "illegal Parameters");
    return result.tostring (); } String fileName = Contentdispositionheader.getfilEname ();
    String Path = type + File.separatorchar + resourceId + File.separatorchar + fileName; 
    Storage path String Dstfilepath = xmlutils.getstring ("root") + path;
    Pictureservice.savefile (FileInputStream, Dstfilepath);

    Logger.info ("Success Save pic file, Dstfilepath =" + Dstfilepath); 
    String Uripath = xmlutils.getstring ("uriroot") + path;
    Logger.info ("Uripath =" + Uripath);
    Result.put ("Uripath", Uripath);
return result.tostring (); @POST @Path ("/delete") @Produces ("Application/json;charset=utf-8") public void Deletepic (@FormParam ("Uripath") 
    String uripath) {string uriroot = xmlutils.getstring ("Uriroot");
    String path = uripath.substring (Uriroot.length ());
    String Dstfilepath = xmlutils.getstring ("root") + path;
Pictureservice.deletefile (Dstfilepath);
 }

Pictureservice.java interface

    public void SaveFile (InputStream fileinputstream, String dstfilepath);

    public void DeleteFile (String dstfilepath);

Pictureserviceimpl.java Implementation Class

Private final Log logger = Logfactory.getlog (Pictureserviceimpl.class);
    @Override public void SaveFile (InputStream fileinputstream, String dstfilepath) {OutputStream outputstream = null;
        try {File File = new file (Dstfilepath);
            if (!file.exists ()) {if (!file.getparentfile (). exists ()) {File.getparentfile (). Mkdirs ();
            } outputstream = new FileOutputStream (new File (Dstfilepath));
            int read = 0;

            byte[] bytes = new byte[1024];
            OutputStream = new FileOutputStream (new File (Dstfilepath));
            while (read = Fileinputstream.read (bytes))! =-1) {outputstream.write (bytes, 0, read);
        }}else{Logger.info ("the pic already exist.");
        }} catch (IOException e) {logger.error (e);
    E.printstacktrace ();
            }finally{try {fileinputstream.close (); OutputStream.Flush ();
        Outputstream.close ();
            } catch (IOException e) {logger.error ("Close stream defeat");
        E.printstacktrace ();
    }}} @Override public void DeleteFile (String dstfilepath) {File File = new file (Dstfilepath);
    File.delete ();
File.getparentfile (). Delete ();
 }

Delete Here there is still a problem, is the use of the above Jersey interface upload good picture has been occupied by the JVM, resulting in unable to delete, but I still do not see where the resources are not released ~ ~

A portion of the code in the corresponding SPRINGMVC by invoking the Jersey interface above

    try {String upload_host = "localhost:8080";

        String Pic_upload_uri = "http:/" + Upload_host + "/xxx/upload"; Multipartentitybuilder Entitybuilder = Multipartentitybuilder.create ();// Org.apache.http.entity.mime.MultipartEntityBuilder//type and ContentID are used to generate a storage path in the above interface Entitybuilder.addtextbod
        Y ("type", type);
        Entitybuilder.addtextbody ("ResourceId", contentId);
        ContentType ContentType = Contenttype.parse (Poster.getcontenttype ());
        String fileName = Poster.getoriginalfilename ();

        Entitybuilder.addbinarybody ("File", Poster.getinputstream (), ContentType, fileName); HttpClient client = new HttpClient ();//self-encapsulated HTTP Tool class String Loadresult = Client.post (Pic_upload_uri, Entitybuilde R.build ());//If the upload succeeds, it returns a JSON-formatted string containing a Uripath//using the Jackson parse to return the result jsonnode node = new Objectmapper (). Readtree
        (Loadresult);
        Uripath = Node.get ("Uripath"). Astext (); Logger.info ("Load pic success! Uripath= "+ Uripath); } catch (Exception e) {logger.error ("Load pic error!
    Reason: "+ e.getmessage ());
 }

Above, the implementation of the image upload service, basic and business-independent, but the way to call is still not good, URL path is not well configured, directly written in the code, but also need to change.

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.