Upload images from android to qiniu cloud storage server,

Source: Internet
Author: User

Upload images from android to qiniu cloud storage server,

I believe that many developers will store images on qiniu. My web site also stores images on qiniu. for image-based websites, this can save a lot of bandwidth.

The key to uploading images to qiniu server is to obtain the upload credential uploadToken. It is too insecure to directly put the AccessKey and Secret on the client, which is easy to decompile. Therefore, an uploadToken needs to be dynamically generated on the server based on the AccessKey and Secret, and then transmitted back to the client. The client uploads the image to qiniu server through this uploadToken.

1. Generate uploadToken on the server

// Upload the image to qiniu start $ bucket = 'qiniu space name'; $ expires = 3600; $ accessKey = 'go to qiniu view '; $ secretKey = <span style = "font-family: Arial, Helvetica, sans-serif;"> 'check qiniu '; </span> $ client = new QiniuClient ($ accessKey, $ secretKey); $ flags = array (); $ scope = $ bucket; $ deadline = time () + $ expires; $ flags ['process'] = $ scope; $ flags ['demoline'] = $ deadline; $ flags ['returnbody'] = null; echo $ client-> uploadToken ($ flags );

Pay attention to the bucket: qiniu space name and deadline: uploadToken expiration time. For details, refer to the official website upload credential introduction.

UploadToken ($ flags) is a self-encapsulated function used to generate an upload credential.

<pre name="code" class="html"><span style="white-space:pre"></span>public function uploadToken($flags)<span style="white-space:pre"></span>{<span style="white-space:pre"></span>if(!isset($flags['deadline']))<span style="white-space:pre"></span>$flags['deadline'] = 3600 + time();<span style="white-space:pre"></span>$encodedFlags = self::urlsafe_base64_encode(json_encode($flags));<span style="white-space:pre"></span>$sign = hash_hmac('sha1', $encodedFlags, $this->secretKey, true);<span style="white-space:pre"></span>$encodedSign = self::urlsafe_base64_encode($sign);<span style="white-space:pre"></span>   <span style="white-space:pre"></span>$token = $this->accessKey.':'.$encodedSign. ':' . $encodedFlags;<span style="white-space:pre"></span>    <span style="white-space:pre"></span>return $token;<span style="white-space:pre"></span>}
<span style="white-space:pre"></span>public static function urlsafe_base64_encode($str){<span style="white-space:pre"></span>    $find = array("+","/");<span style="white-space:pre"></span>    $replace = array("-", "_");<span style="white-space:pre"></span>    return str_replace($find, $replace, base64_encode($str));<span style="white-space:pre"></span>}


2. Download qiniu-android-sdk-7.0.0.jar and android-async-http-1.4.6 and import the project

Third, upload images to android

Since network connection is not allowed in the main thread after Android4.0, a new thread is required to obtain the upload credential.

<Span style = "white-space: pre"> </span>/** upload an image to qiniu */private void uploadImg () {new Thread (new Runnable () {@ Overridepublic void run () {// obtain the upload credential uploadTokenString token = getUploadToken (); // the path for storing the SD card image on the mobile phone: String imgPath = ""; try {imgPath = FileUtil. getBasePath () + "/test.jpg";} catch (IOException e) {e. printStackTrace ();} if (token! = Null) {String data = imgPath; // The image name is the current date + Random Number Generation String key = getRandomFileName (); UploadManager uploadManager = new UploadManager (); uploadManager. put (data, key, token, new UpCompletionHandler () {@ Overridepublic void complete (String arg0, ResponseInfo info, JSONObject response) {// TODO Auto-generated method stubLog. I ("qiniu", info. toString () ;}}, null) ;}else {Log. I ("fail", "Upload Failed ");}}}). start ();}

FileUtil. getBasePath () is used to obtain the basic path of the SD card. getRandomFileName () generates a random number to name the uploaded image. I will skip this step.

You can use httpget to directly communicate with the server and obtain the data generated in step 1. (Note that is a special IP Address Provided by the simulator. It is equivalent to testing IP127.0.0.1 on the computer side)

/** Obtain the upload credential uploadtoken */<span style = "white-space: pre"> </span> private String getUploadToken () <span style = "white-space: pre"> </span> {<span style = "white-space: pre "> </span> HttpClient client = new DefaultHttpClient (); <span style =" white-space: pre "> </span> StringBuilder builder = new StringBuilder (); <span style = "white-space: pre"> </span> <span style = "white-space: pre"> </span> HttpGet myget = new HttpGet ("Http: // php "); <span style =" white-space: pre "> </span> try {<span style =" white-space: pre "> </span> HttpResponse response = client.exe cute (myget); <span style =" white-space: pre "> </span> BufferedReader reader = new BufferedReader (new InputStreamReader (<span style =" white-space: pre "> </span> response. getEntity (). getContent (); <span style = "white-space: pre"> </span> for (String s = Reader. readLine (); s! = Null; s = reader. readLine () {<span style = "white-space: pre"> </span> builder. append (s); <span style = "white-space: pre"> </span >}< span style = "white-space: pre "> </span> return builder. toString (); <span style = "white-space: pre"> </span>} catch (Exception e) {<span style = "white-space: pre "> </span> Log. I ("url response", "false"); <span style = "white-space: pre"> </span> e. printStackTrace (); <span style = "white-space: pre"> </span> return null; <span style = "white-space: pre "> </span >}< span style =" white-space: pre "> </span>}

The LOG shows Qiniu -- success, indicating that the upload is successful.

Related Article

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.