Multipart/form-data image Upload Implementation method (upload file to nimg)

Source: Internet
Author: User
Tags uuid
Summary: Multipart/form-data image upload implementation methods and the use of System.getproperty ("Line.separator") Considerations

In the implementation of Multipart/form-data image upload, you need to use \ r \ n to separate each row, in the Java implementation of Multipart/form-data image upload can be used System.getproperty (" Line.separator ") to split each row. But if you want to use the code for Android, remember that you can't use System.getproperty ("Line.separator") to split each row because in Android System.getproperty (" Line.separator ") is \ n, in Java it is \ r \ n.

Therefore, we do not recommend the use of System.getproperty ("Line.separator"), there will be some unexpected problems, and the emergence of these problems are not easy to trace back to System.getproperty ("Line.separator") To use.

The following upload code can be used for Java and Android, the code is for NIMG implementation, if you need to use with other environments, change the "Upload parameters" code for the environment.

Uploadimage.java

package cloud.test;
import java.io.bufferedreader;
import java.io.bytearrayoutputstream;
import java.io.dataoutputstream;
import java.io.file;
import java.io.fileinputstream;
import java.io.ioexception;
import java.io.inputstreamreader;
import java.net.httpurlconnection;
import java.net.url;
import java.util.uuid; /**  *  Photo Upload  *  @author  cloud  *  @version  1.0  */public class  uploadimage {   private static final string multipart_form_data=
"Multipart/form-data";
   private static final String TWOHYPHENS =  "--";     private static final String BOUNDARY =  "----------------
-----------"+uuid.randomuuid ();
    private static final String LINEEND =  "\ r \ n";     private static&nbsP;final string formname= "UserFile";
         private String actionUrl;
    private int timeout;
         private String fileName;
    private byte[] data;
    private String imageType;          /**      *  initialization image upload Tool       *  @param  actionUrl -  Image storage address      *  @param  timeout -  picture upload timeout time   (ms)      */    public  uploadimage (string actionurl,int timeout) {       
This.actionurl=actionurl;
       this.timeout=timeout;    &NBSP}          /**      *  Set upload content      *  @param  fileName -  picture name       *  @param  data -  photo content      *  @param  imageType -  Picture Format      */    public void  SetData (string filename,byte[] data,imagetype imagetype)  throws exception{ 
      this.fileName=fileName;
       this.data=data;
       this.imagetype=imagetype.getvalue ();                if (imagetype!=null) {           string extension =imagetype.getvalue ().
SUBSTRING (Imagetype.getvalue (). IndexOf ("/") +1, imagetype.getvalue (). Length ());           this.fileName=filename+ "."
+extension; &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP}     }           /**      *  upload      *  @return  -  format <br/>      * {<br/>      * &nbsp; &nbsp;&nbsp;&nbsp; " Code ": 200,<br/>      * &nbsp;&nbsp;&nbsp;&nbsp;" Msg ": " upload success! ",<br/>      * &nbsp;&nbsp;& nbsp;&nbsp; " Data ": {<br/>      * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp ;&nbsp;&nbsp;&nbsp; " T ": " PNG,<br/>      * &nbsp;&nbsp;&nbsp;&nbsp;& nbsp;&nbsp;&nbsp;&nbsp; " UserPath ": ",<br/>      * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; " MD5 ": " 6F8B47EC3B8EA08335CB6E13CBBE96DC ",<br/>      * &nbsp;& nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; " URL ": " 01/6f8b47ec3b8ea08335cb6e13cbbe96dc.png <br/>      * &nbsp; &nbsp;&nbsp;&nbsp;} <br/>      * }<br/>      */     public string upload () {       return upload (null,null)
; &NBSP;&NBSP;&NBSP;&NBSP}               /**  
    *  upload      *  @param  actType -  image Processing command      *  @param  param -  Picture processing parameters      *  @return  -  format <br/>      * {<br/>      * &nbsp;&nbsp;&nbsp;&nbsp; " Code ": 200,<br/>      * &nbsp;&nbsp;&nbsp;&nbsp;" Msg ": " upload success! ",<br/>      * &nbsp;&nbsp;& nbsp;&nbsp; " Data ": {<br/>      * &nbsp;&nbsp;&nbsp;&nbsp;&nbsp ;&nbsp;&nbsp;&nbsp; " T ": " PNG,<br/>      * &nbsp;&nbsp;&nbsp;&nbsp;& nbsp;&nbsp;&nbsp;&nbsp; " UserPath ": ",<br/>      * &nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp; " MD5 ": " 6F8B47EC3B8EA08335CB6E13CBBE96DC ",<br/>      * &nbsp;& nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; " URL ": " 01/6f8b47ec3b8ea08335cb6e13cbbe96dc.png "<br/>      * &nbsp;&nbsp;&nbsp;&nbsp;} <br/>      * }<br/>      */     public string upload (acttype acttype,string param) {     
  HttpURLConnection conn = null;
        DataOutputStream output = null;
        BufferedReader input = null;                 try { 
         url url = new url (ACTIONURL);             conn =  (HttpURLConnection)
 url.openconnection ();             conn.setconnecttimeout (timeout);
            conn.setdoinput (TRUE);
            conn.setdooutput (TRUE);
            conn.setusecaches (FALSE);
            conn.setrequestmethod ("POST");             conn.setrequestproperty ("Connection",
  "Keep-alive");             conn.setrequestproperty ("Content-Type"
, multipart_form_data +  ";  boundary="  + boundary);
            conn.connect ();             output = new 
DataOutputStream (Conn.getoutputstream ());                          StringBuilder 
Sb = new stringbuilder ();             if (Acttype!=null&&param!=null) {             /**                 *  Upload Parameters                 */        
      sb.append (Twohyphens + boundary + lineend);               sb.append ("
Content-disposition: form-data; name=\ "act\" " + lineend");
              sb.append (LINEEND);                sb.append (Acttype.getvalue ()  + lineend);               output.writebytes (
Sb.tostring ());                    
          sb = new stringbuilder ();               sb.append (TWOHYPHENS 
+ boundary + lineend);               sb.append ("
Content-disposition: form-data; name=\ "param\" " + lineend");
              sb.append (LINEEND);               sb.append (param +
 lineend);                output.writebytes (Sb.toString ());             }                        /**             *  Upload Pictures             */          sb = new 
StringBuilder ();           sb.append (twohyphens + boundary +
 lineend);           sb.append ("content-disposition: form-data;  name=\ ""  + FORMNAME +  " filename=\" " + fileName + " "" "
 + lineend);           sb.append ("content-type: " + imagetype + lineend);
          sb.append (Lineend);
           output.writebytes (Sb.toString ());            output.write (Data, 0, data.length)
;
           output.writebytes (LINEEND);                /**              *  Upload End              */           
Output.writebytes (Twohyphens + boundary + twohyphens + lineend);
           output.flush ();                        /**             *  return information            */  
         int code = conn.getresponsecode ();
&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;SYSTEM.OUT.PRINTLN (code);            if  (code != 200)  {                throw new  RuntimeException ("Request"  + actionUrl + ) failed.
");            }             input = new bufferedreader (New inputstreamreader (
Conn.getinputstream ()));            stringbuilDer response = new stringbuilder ();
           String oneLine;            while  (oneline =  Input.readline ())  != null)  {           
    response.append (Oneline + lineend);            }        
    return response.tostring ();        } catch  (ioexception e)  {   
         throw new runtimeexception (e);         } finally {             try {&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBsp;      if  (output != null)  {     
               output.close ();                 }                  if  (input !=  null)  {               
     input.close ();                 }   
          } catch  (ioexception e)  {                 throw new
 runtimeexception (e);           &NBSP;&NBSP}             if  (conn !=  null)  {               
 conn.disconnect ();             }          }    &nbsp}}

Acttype.java

Package cloud.test;
/**
* Image upload Command
* @author Cloud
* @version 1.0 * * Public
enum Acttype {
/**
* Rotation
* *
ROTATE ("ROTATE"),
/**
* * Cut
/crop ("crop"),
/**
* Zoom
* *
RESIZE ("RESIZE");
private String value;
Private Acttype (String value) {
this.value=value;
Public
String GetValue () {return
value;
}
}

Imagetype.java

package cloud.test; /**  *  Picture format  *  @author  cloud  *  @version  1.0  */public enum
 imagetype {   /**     * jpg Format     */    jpg ("Image/jpg"),    /**     * png format      */   png ("Image/png"),    /**     * gif format      */   gif ("Image/gif"),    /**     * 
JPEG format     */   jpeg ("Image/jpeg");
       private String value;        private imagetype (string value)  {    
  this.value=value; &NBSP;&NBSP;&NBSP}    public string getvalue ()  {     
 return value;     }} 

        source code, Jar Pack, description document download address Http://pan.baidu.com/s/1ntxMvBb

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.