Android/ios two ways to upload common images

Source: Internet
Author: User
Tags decrypt

Android/ios two ways to upload common images:

1. File server uploaded to the server (fileserver)

Principle: the way to upload to the file server is to set up a file server on the server, configure a good path (URL), the path is the path we will upload pictures, after the successful configuration through the Http+post mode upload to the file server, and the file server will return an image ID, This ID is the unique identity of the image, and writes the ID to the database to save it, and only need to take this ID with you when it is necessary to download the image.

Two core issues:

(1) Server: Configure Fileserver, and write processing response to upload the image of the code, this is worth to go online research;

(2) Customer Service: Write the code of the HTTP upload file, I post the upload core code:

/**
  *
  * @param params
  *          Common parameters for    pass
  * @param uploadfile
  *             file name to upload
  * @param fileformname
  *             need to upload a file name in the form
  * @param newfilename
  *             uploaded file name, do not fill in the name of UploadFile
  * @param urlstr
  *             the path of the uploaded server
  * @throws ioexception
  */

public void Uploadform (map<string, string> params, String fileformname,
   file uploadfile , string NewFileName, String urlstr, Context mcontext)
   throws ioexception {
  if ( NewFileName = = NULL | | Newfilename.trim (). Equals ("")) {
   newfilename = Uploadfile.getname ();
  }

  stringbuilder sb = new StringBuilder ();
  /**
   * Normal form data
   */
  if (params! = null)
    for (String key:params.keySet ()) {
    sb.append ("--" + boundary + "\ r \ n");
    sb.append ("Content-disposition:form-data; Name=\ "" + key
      + "\" "+" \ r \ n ");
    sb.append ("\ r \ n");
    sb.append (Params.get (key) + "\ r \ n");
   }
  /**
   * Upload file header
   */
  sb.append ("--" + boundary + "\ r \ n");
  sb.append ("Content-disposition:form-data; Name=\ "" + fileformname
    + "\"; filename=\ "" + NewFileName + "\" "+" \ r \ n ");
  sb.append ("content-type:image/jpeg" + "\ r \ n");//If the server side has file type validation, you must explicitly specify ContentType
   Sb.append ("\ r \ n");

  byte[] HeaderInfo = sb.tostring (). GetBytes ("UTF-8");
  byte[] Endinfo = ("\r\n--" + boundary + "--\r\n"). GetBytes ("UTF-8");
  system.out.println (sb.tostring ());
  url url = new URL (urlstr);
  httpurlconnection conn = (httpurlconnection) url.openconnection ();
  conn.setrequestmethod ("POST");
  conn.setrequestproperty ("Content-type", "
    " multipart/form-data; boundary= "+ boundary);
  conn.setrequestproperty (
     "Content-length",
     string.valueof (Headerinfo.length + uploadfile.length ()
      + Endinfo.length));
  conn.setdooutput (true);

  outputstream out = Conn.getoutputstream ();
  inputstream in = new FileInputStream (uploadfile);
  /** file Total size **/
  onuploadprocesslistener.initupload ((int) uploadfile.length ());
  out.write (HeaderInfo);
  byte[] buf = new byte[1024];
  int Len;
  int curlen = 0;//Current length
  while (len = In.read (BUF))! =-1) {
    Out.write (buf, 0, Len);
   curlen + = len;
   /** the size of the upload progress value **/
   onuploadprocesslistener.onuploadprocess (curLen);
  }

Out.write (Endinfo);
In.close ();
Out.close ();
String result = "";
int code = Conn.getresponsecode ();
if (code = = 200) {
System.out.println ("Upload success");
InputStream input = Conn.getinputstream ();
StringBuffer sb1 = new StringBuffer ();
int SS;
while (ss = Input.read ())! =-1) {
Sb1.append ((char) SS);
}
result = Sb1.tostring ();
callback method
SendMessage (1, result);

Saveuploadfile (mcontext, result);
}
Toast.maketext (Mcontext, "results returned after uploading:" + result, +). Show ();

}

Here the result is the return of the image ID, the code to see for themselves, is the mode of simulation browser upload, if you are not quite clear can first understand the browser post mode.

2. Upload the database to the server

Principle: The principle is very simple, that is, the image is encrypted in the form of Base64 to the form of parameters to the server and write directly to the database, need to use the time to directly obtain this field and decrypt it .

Base64 Encryption:

byte[] Bpic = tools.bitmap2bytes (bitmap);

String mskinimage = Base64helper.encode (bpic);

Http+post+para Upload

list<basicnamevaluepair> pairs = new arraylist<basicnamevaluepair> ();

Pairs.add (New Basicnamevaluepair ("Skinimage", Mskinimage));

Here is the upload

Httphelper.getdataencyption (Tools.getrequrl (), pairs, mhandler);

This way the upload is successful and then directly into the database, I post the Base64 encryption and decryption code:

public class Base64helper {
/**
* Coded encryption
* @param ByteArray
* @return
*/
public static String encode (byte[] byteArray) {
return new String (Base64.encodetostring (ByteArray, Base64.default));
}

/**
* Decode-Decrypt
* @param base64encodedstring
* @return
*/
public static byte[] Decode (String base64encodedstring) {
byte[] bb = null;
try {
bb = Base64.decode (base64encodedstring, Base64.default);
} catch (Exception e) {
TODO auto-generated Catch block
E.printstacktrace ();
}
return BB;
}

}

In this way, two ways to upload the picture is over, of course, the first kind of I was focused on the principle, configuration service side of the not detailed give, this piece I think is worth our research, there is a common need to exchange, research, sharing.

This article is from the "Suck on self-renewal" blog, please be sure to keep this source http://wyong.blog.51cto.com/1115465/1535648

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.