Android using seven cow cloud storage for picture upload download of instance code _android

Source: Internet
Author: User
Tags crc32 crc32 checksum file url hash throwable

Android development of the image store is more time-consuming things, and the use of the third party of the seven Neu Yun, it can be a good solution to these worries, recently I was also learning seven Cow SDK, will use the process in this record down, easy to use later.

First say seven Neu Yun storage principle, above this picture is the official schematic diagram, the expression of course more clear.

As you can see, there are five big steps you can take to upload pictures:

1. Client user login to app's account system;

2. Before the client uploads the file, it is necessary to apply to the business Server for seven cattle upload voucher, this voucher is generated by Business Server using seven-cow service-side SDK;

3. Clients use the Client SDK provided by seven cows, call upload method upload file, upload the method must have upload credentials and file content (because seven cattle allowed size of 0 files, so file upload, recommended check file size.) If the business does not allow the file size of 0, then the need to detect themselves;

4. The client file uploaded to seven cows, the optional operation is seven cattle callback Business Server, (that is, seven cattle to send file information related to the POST request to the upload strategy within the specified callback address);

5. Business Server reply to seven cattle callback request, give JSON format reply content (must be JSON format reply), this reply content will be seven cow forward to client;

OK, seven Neu Yun operation principle to make clear, careful understanding is not very troublesome, below we start integration operation.

First, download the official SDK

Reference to the seven Neu Yun official website (http://www.qiniu.com/?utm_campaign=baiduSEM&utm_source=baiduSEM&utm_medium=baiduSEM&utm_ CONTENT=BAIDUSEM) Download the specified SDK, in fact, according to the official MAVEN address to download a good, after downloading the latest version of QINIUSDK, is it possible to busy copy development documents in the corresponding code?

Do not worry, in addition to rely on QINIU-ANDROID-SDK, but also rely on happy-dns,okhttp,android-async-http, so there are four dependent packages altogether. Here is a small tip, if the download of those things trouble, you can download the official demo, and then put all of the dependencies inside their own projects, of course, the premise is that you need to know what is what.

Second, listing file add permissions

Note: If you use Android5.0 and its version, the permission is to be applied in code.

<uses-permission android:name= "Android.permission.INTERNET"/>

Third, define variables

Before we write and upload the code, we need to define the following variables.

Private TextView title; Display the results
of the upload private imageview image;//display downloaded picture content
private ProgressDialog progressdialog;//Upload progress prompt box
private Boolean isprogresscancel; Do you want to cancel uploading or downloading
private UploadManager uploadmanager//Seven Cow SDK upload manager
private uploadoptions uploadoptions; /Seven Cow SDK upload options
private Myupcompletionhandler mhandler//Seven Cow SDK upload return monitor
private Upprogresshandler Upprogresshandler; Seven Cattle SDK upload progress monitoring
private upcancellationsignal upcancellationsignal;//Seven Cow SDK upload process cancel monitor
private final static String Token_url = "http://xxx.xxx.xxx/x/"; Server request token URL
private string Uptoken//server request token value
private string upkey;//Upload file key value
private byte[] Uploaddata; Uploaded files

Four, upload the picture

Seven cattle server can upload three types, including byte[] type of picture, String type file path, file type files;

(i) Request token from the server

private void Gettokenfromservice () {
//simulate obtaining uptoken
Uptoken = "12343232313123" from the server;
Synchttpclient client = new Synchttpclient ();
Client.get (Token_url, New Texthttpresponsehandler () {
@Override public
void onfailure (int statusCode, header[ ] headers, String responsestring, Throwable throwable) {
log.e ("Error", "OnFailure: Server Request token failed");
@Override public
void onsuccess (int statusCode, header[] headers, String responsestring) {
try {
Jsonobject jsonobject = new Jsonobject (responsestring);
Parse the resulting JSON string, get token value
Uptoken = jsonobject.getstring ("token");
} catch (Jsonexception e) {
E.printstacktrace ();}}}
);

(ii) initialization of upload parameters

private void InitData () {
gettokenfromservice ();
Upkey = Getpicture ();
UploadManager = new UploadManager ();
Upprogresshandler = new Upprogresshandler () {
/**
* @param key upload upkey;
* @param percent upload progress;
@Override Public
void Progress (String key, double percent) {
progressdialog.setprogress ((int) ( Uploaddata.length * percent));
}
;
upcancellationsignal = new Upcancellationsignal () {
@Override public
boolean iscancelled () {
return Isprogresscancel;
}
;
Define options for data or file uploads
uploadoptions = new Uploadoptions (
NULL,//extended parameters, user-defined parameters beginning with <code>x:</code>
"Mime_type",//Specify mimetype true of uploaded files,//
whether to enable upload content CRC32 checksum
upprogresshandler,//upload content Progress processing
Upcancellationsignal//Cancel the upload signal
);
Mhandler = new Myupcompletionhandler ();
}

(iii) Start asynchronous thread, upload image file

public void Clickpost (view view) {
if (Textutils.isempty (Uptoken)) {
Toast.maketext (mainactivity.this, " Getting token values from the network, please later ... ", Toast.length_short). Show ();
return;
}
New Thread (New Runnable () {
@Override public
void Run () {
Progressdialog.setmax (uploaddata.length);
Progressdialog.show ();
Uploadmanager.put (Uploaddata, Upkey, Uptoken, Mhandler, uploadoptions);
}
);

Five, download pictures

The SDK does not provide a functional interface for downloading files, because file downloads are a standard HTTP get process. Developers simply understand the composition of the resource URI to easily build the resource URI and, if necessary, add the download voucher, then use the HTTP GET request to obtain the appropriate resource.

The upper italic is copied from the QINIUSDK official website's guidance document, so the download method is relatively simple.

After the public void Clickdown (view view) {
//Picture is uploaded to seven cows,//the
default will be the hash of the file and the key (file name) in response to return,
//Then in the space set-> domain name settings, Find the space domain name,
//through the http://space domain name/key form, get the file URL.
String fileName = "xxx.xxx.xx/xx";
String Downurl = "http://" + fileName + "/" + Upkey;
Synchttpclient client = new Synchttpclient ();
Client.get (Downurl, New Binaryhttpresponsehandler () {
@Override public
void onsuccess (int statusCode, Header [] headers, byte[] binarydata) {
if (binarydata!= null) {
Image.setimagebitmap ( Bitmapfactory.decodebytearray (binarydata, 0, Binarydata.length));
}
@Override public
void onfailure (int statusCode, header[] headers, byte[] binarydata, throwable error) {
LOG.E ( "Error", "OnFailure: Picture Download Failed");
}

Vi. Summary of documentation

Sometimes read 100 times text introduction, also better read fuck code, so I still involved in the file source also copy come over a copy, later also convenient to see.

(i) Mainactivity.class

Package com.example.administrator;
Import Android.app.ProgressDialog;
Import Android.content.DialogInterface;
Import Android.graphics.BitmapFactory;
Import Android.os.Bundle;
Import android.support.v7.app.AppCompatActivity;
Import Android.text.TextUtils;
Import Android.util.Log;
Import Android.view.View;
Import Android.widget.ImageView;
Import Android.widget.TextView;
Import Android.widget.Toast;
Import COM.EXAMPLE.ADMINISTRATOR.MYQINIUDEMO.R;
Import Com.loopj.android.http.BinaryHttpResponseHandler;
Import com.loopj.android.http.SyncHttpClient;
Import Com.loopj.android.http.TextHttpResponseHandler;
Import Com.qiniu.android.http.ResponseInfo;
Import com.qiniu.android.storage.UpCancellationSignal;
Import Com.qiniu.android.storage.UpCompletionHandler;
Import Com.qiniu.android.storage.UpProgressHandler;
Import Com.qiniu.android.storage.UploadManager;
Import com.qiniu.android.storage.UploadOptions;
Import org.json.JSONException;
Import Org.json.JSONObject; Import Cz.msebera.android.httpcliEnt.
Header; public class Mainactivity extends appcompatactivity {private TextView title;//Display upload result private imageview image;//display downloaded pictures inside Rong Private ProgressDialog ProgressDialog; Upload Progress Prompt Box private Boolean isprogresscancel; Whether to cancel uploading or downloading private uploadmanager UploadManager in the process of network request; Seven Cattle SDK upload manager private uploadoptions uploadoptions; Seven Cattle SDK upload options private Myupcompletionhandler mhandler; Seven Cattle SDK upload back to monitor private Upprogresshandler upprogresshandler; Seven Cattle SDK upload progress monitoring private upcancellationsignal upcancellationsignal; Seven Cattle SDK upload process to cancel the listener private final static String Token_url = "http://xxx.xxx.xxx/x/"; The server requests token URL private String uptoken; Server requests token value private String upkey; Upload the file key value private byte[] uploaddata;
The uploaded file @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);
Setcontentview (R.layout.activity_main);
Initview ();
InitData (); private void InitData () {gettokenfromservice (); upkey = Getpicture (); UploadManager = new UploadManager (); Upprogressha Ndler = new Upprogresshandler () {/** * @param key upload upkey; * @param percent upload progress;/@Override public void Progress (String K
EY, double percent) {progressdialog.setprogress ((int) (UPLOADDATA.LENGTH * percent));}; upcancellationsignal = new Upcancellationsignal () {@Override public boolean iscancelled () {return isprogresscancel;}}
; Define options for data or file uploads uploadoptions = new uploadoptions (NULL,//extension parameters, user-defined parameter "Mime_type" at the beginning of the <code>x:</code>/
/Specify the upload file mimetype true,//whether to enable the upload content CRC32 check upprogresshandler,//upload content Progress processing upcancellationsignal//cancel upload signal);
Mhandler = new Myupcompletionhandler (); Private String Getpicture () {///simulate the byte array of uploaded images and return the filename uploaddata = new Byte[]{1, 2, 3, 1, 2, 3, 3, 4, 2, 1
n "Upload.txt";
private void Gettokenfromservice () {//simulation obtains uptoken from the server Uptoken = "12343232313123";
Synchttpclient client = new Synchttpclient (); Client.get (Token_url, New Texthttpresponsehandler () {@Override public void onfailure (int statusCode, header[] headers, S Tring RespoNsestring, Throwable throwable) {log.e ("Error", "OnFailure: Server Request token failed"); @Override public void onsuccess (int statusc Ode, header[] headers, String responsestring) {try {jsonobject = new Jsonobject (jsonobject);//parse the resulting JSON string
, get token value Uptoken = jsonobject.getstring ("token");
catch (Jsonexception e) {e.printstacktrace ();}}
}); private void Initview () {title = (TextView) Findviewbyid (r.id.title); image = (ImageView) Findviewbyid (r.id.image); INI
Tprogressbar ();
private void Initprogressbar () {progressdialog = new ProgressDialog (mainactivity.this);
Progressdialog.setprogressstyle (progressdialog.style_horizontal);
Progressdialog.settitle ("Progress hint");
Progressdialog.setbutton (Dialoginterface.button_negative, "Cancel", new Dialoginterface.onclicklistener () {@Override
public void OnClick (Dialoginterface dialog, int which) {Isprogresscancel = true;}}); /** * Click the button, start file Upload * * @param view */public void Clickpost (view view) {if (Textutils.isempty (Uptoken)) {Toast.makeText (Mainactivity.this, "getting the token value from the network, please later ...", Toast.length_short). Show ();
Return New Thread (New Runnable () {@Override public void run () {Progressdialog.setmax (uploaddata.length); progressdialog.show
();
Uploadmanager.put (Uploaddata, Upkey, Uptoken, Mhandler, uploadoptions);
}
}); /** * Click the button, start the file download * * @param view/public void Clickdown (view view) {//Picture uploaded to seven cattle,//The default will be the file's hash and key (file name) in response back,//
Then in the space set-> domain name setting, find the space domain name,//through http://space domain name/key form, get file URL.
String fileName = "Xxx.xxx.xx/xx";
String Downurl = "http://" + fileName + "/" + Upkey;
Synchttpclient client = new Synchttpclient (); Client.get (Downurl, New Binaryhttpresponsehandler () {@Override public void onsuccess (int statusCode, header[] headers, b Yte[] BinaryData {if (binarydata!= null) {Image.setimagebitmap (Bitmapfactory.decodebytearray, 0,
Binarydata.length));  } @Override public void onfailure (int statusCode, header[] headers, byte[] binarydata, throwable error) {LOG.E ("error") "OnFailure: Picture Download Failed");
}
}); /** * Custom Upload Complete Listening class * Implement the Upcompletionhandler interface in QINIUSDK * * * public class Myupcompletionhandler implements Upcompletionhandl ER {/** * @param key upload upkey; * @param the upload information represented by the info JSON string, including the use version, request status, request ID, etc. * @param response the file information represented by the JSON string, including the file hash code, File MIME type, file size and other information; */@Override public void complete (String key, Responseinfo info, jsonobject response) {PROGRESSDIALOG.D
Ismiss ();
Title.settext (key + "!\n" + info + "!\n" + response + "!"); }
}
}

(ii) activity_main.xml

 <?xml version= "1.0" encoding= "Utf-8"?> <linearlayout "android:orientation=" Vertical "xmlns:android=" http://schemas.android.com/apk/res/android "xmlns:tools=" http://schemas.android.com/ Tools "Android:layout_width=" Match_parent "android:layout_height=" match_parent "android:gravity=" Center_ Horizontal "tools:context=" com.example.administrator.myqiniudemo.MainActivity "> <textview android:id=" @+id/ Title "Android:layout_width=" Wrap_content "android:layout_height=" wrap_content "android:text=" Hello Qiniu! "
/> <button android:layout_width= "wrap_content" android:layout_height= "wrap_content" android:text= "Upload pictures" android:onclick= "Clickpost"/> <button android:layout_width= "Wrap_content" android:layout_height= Content "android:text=" Download Picture "android:onclick=" Clickdown "/> <imageview android:id=" @+id/image " Width= "Match_parent" android:layout_height= "match_parent"/> </linearlayout> 

The above is a small series of Android to introduce the use of seven cattle cloud storage to upload the image of the download of the example code, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

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.