Instructions for uploading files to Baidu cloud Disk

Source: Internet
Author: User

Figure 1

Figure 2

Figure 3

Figure 4

1. Upload the Baidu cloud disk function, because Baidu developers have not yet enabled the. NET

Therefore, we can only use native rest APIs.

 

Our approach is to call the curl command in C.

2. Curl is an open source file transmission tool that uses the URL syntax in the command line mode. It is widely used in UNIX and multiple Linux distributions, and has dos, Win32, and win64 versions.

To operate curl, we need to introduce libcurlnet. dll.

 

3. for Baidu upload, we need a Baidu account, and we need to apply for the developer feature to go to the home page.

Accesskey and secrectkey are very important.

4. input parameters to obtain the encrypted URL. The following code writes the file to a temporary file under the temp server.

Public static string put (string sobject, httppostedfilebase file) {string content = Flag + "\ n" + "method = put \ n" + "Bucket =" + bucket + "\ n" + "Object =" + sobject + "\ N "; // + "time =" + "\ n" // + "IP =" + "\ n" // + "size =" + "\ n "; string signture = Flag + ":" + accesskey + ":" + httputility. urlencode (myhmac. hmacsha1 (content, secrectkey); string url = "http://bcs.duapp.com/" + bucket + "/" + httputili Ty. urlencode (sobject) + "? Sign = "+ signture; string Path = system. Io. Path. Combine (httpcontext. Current. server. mappath ("~ /Temp "), system. io. path. getfilename (file. filename); stream = file. inputstream; // converts stream to byte [] Byte [] bytes = new byte [stream. length]; stream. read (bytes, 0, bytes. length); // set the current stream position to the starting stream of the stream. seek (0, seekorigin. begin); filestream FS = new filestream (path, filemode. create); binarywriter BW = new binarywriter (FS); BW. write (bytes); FS. close (); filestream FSS = new filestream (path, filemode. open, fileaccess. read, fileshare. read); try {curl. globalinit (INT) curlinitflag. curl_global_all); easy = new easy (); easy. readfunction Rf = new easy. readfunction (myhmac. onreaddata); easy. setopt (curloption. curlopt_readfunction, RF); easy. setopt (curloption. curlopt_readdata, FSS); easy. writefunction WF = new easy. writefunction (myhmac. onwritedata); easy. setopt (curloption. curlopt_url, URL); easy. setopt (curloption. curlopt_upload, 1); easy. setopt (curloption. curlopt_infilesize, bytes. longlength); easy. setopt (curloption. curlopt_verbose, 1); easy. setopt (curloption. curlopt_writefunction, WF); // easy. setopt (curloption. curlopt_writedata, WF); easy. debugfunction df = new easy. debugfunction (myhmac. ondebug); easy. setopt (curloption. curlopt_debugfunction, DF); easy. setopt (curloption. curlopt_verbose, true); curlcode code = easy. perform (); easy. cleanup (); FSS. close (); curl. globalcleanup (); // delete a temporary file. delete (PATH); return code. tostring () ;}catch (exception ex) {Throw new exception ("error", ex );}}

 

5. This Code is the code that calls libcurlnet to upload.

 

6. The action code calls Baidu to upload put and stores the file name in the session.

Public jsonresult uploadfile (httppostedfilebase [] filedatalist) {list <jsonmodel> listinfo = new list <jsonmodel> (); If (filedatalist! = NULL) {try {foreach (httppostedfilebase file in filedatalist) {string fileextension = path. getextension (file. filename); // file extension string sobject = "/newfolder/" + path. getfilename (file. filename); string Path = system. io. path. combine (server. mappath ("~ /Temp "), system. io. path. getfilename (file. filename); file. saveas (PATH); string code = httpclientutil. doputmethodtoobj <string> (sobject, PATH); // string code = Crul. put (sobject, file); If (code = NULL) {viewmodel = (materialsviewmodel) session ["materialsviewmodel"]; objectfiles of = new objectfiles ();. objecttype = "material"; if (".bmp, .jpg,.htm, .gif ,. PCX ,. TGA ,. EXIF ,. fpx ,. SVG ,. PSD ,. CDR ,. PCD ,. DXF ,. UFO ,. EPS ,. AI ,. raw ". contains (fileextension) {. ispic = true;} else {. ispic = false;}. objectid = "m001"; // Temp value. fieldvalue = sobject; int recno =-1; if (viewmodel. pictureslist. count> 0) {recno = (viewmodel. pictureslist. count + 1) *-1;}. recno = recno; viewmodel. pictureslist. add (of); Session ["materialsviewmodel"] = viewmodel; listinfo. add (New jsonmodel (true, file. filename, "uploaded successfully");} else {listinfo. add (New jsonmodel (false, file. filename, Code) ;}} return JSON (listinfo, jsonrequestbehavior. allowget);} catch (exception ex) {listinfo. add (New jsonmodel (false, "", Ex. message); Return JSON (listinfo, jsonrequestbehavior. allowget) ;}} else {listinfo. add (New jsonmodel (false, "", "Please select a file upload"); Return JSON (listinfo, jsonrequestbehavior. allowget );}}

6. In Figure 4, the delete function can only be deleted from the database, but not from the Baidu cloud disk,

I still don't know how to implement the Code for deleting Baidu cloud. There is too little information in China.

     //public static bool DELETE(string sobject)        //{        //    string content = Flag + "\n"        //      + "Method=DELETE\n"        //      + "Bucket=" + Bucket + "\n"        //      + "Object=" + sobject + "\n";        //    string signture = Flag + ":" + AccessKey + ":" + HttpUtility.UrlEncode(MyHmac.hmacSha1(content, SecrectKey));        //    string url = "http://bcs.duapp.com/" + Bucket + "/" + HttpUtility.UrlEncode(sobject) + "?sign=" + signture;        //    return HttpClientUtil.doDeleteMethod(url);        //}

Upload method to Baidu cloud No. 2

1. We mentioned above that calling the Baidu cloud interface requires adding libcurlnet. dll. libcurlnet. dll is not required here.

2. Baidu uploads code

     public static string GenerateUri(string method, string sobject)        {            string content = Flag + "\n"                           + "Method=" + method + "\n"                           + "Bucket=" + Bucket + "\n"                           + "Object=" + sobject + "\n";            //+ "Time=" + "\n"            //+ "Ip=" + "\n"            //+ "Size=" + "\n";            string signture = Flag + ":" + AccessKey + ":" + HttpUtility.UrlEncode(MyHmac.hmacSha1(content, SecrectKey));            string uri = "http://bcs.duapp.com/" + Bucket + "/" + HttpUtility.UrlEncode(sobject) + "?sign=" + signture;            return uri;        }

 

// Rest @ put method, with the public static t doputmethodtoobj (string _ object, string path) {string uri = generateuri ("put", _ OBJECT ); httpwebrequest wrequest = (httpwebrequest) webrequest. create (URI); wrequest. method = "put"; wrequest. contenttype = "application/JSON; charset = UTF-8"; wrequest. allowwritestreambuffering = false; // wrequest. timeout = 10000; filestream readin = new filestream (path, filemode. open, fileaccess. read); readin. seek (0, seekorigin. begin); // move to the start of the file. wrequest. contentlength = readin. length; // set the Content Length header to the size of the file. byte [] filedata = new byte [readin. length]; // read the file in 2 kb segments. int dataread = 0; stream tempstream = wrequest. getrequeststream (); do {If (filedata. length <= 2048) dataread = readin. read (filedata, 0, filedata. length); else dataread = readin. read (filedata, 0, 2048); If (dataread> 0) // we have data {tempstream. write (filedata, 0, dataread); // array. clear (filedata, 0, filedata. length); // clear the array .}} while (dataread> 0); httpwebresponse wresponse = (httpwebresponse) wrequest. getresponse (); // read your response data here. // close all streams. readin. close (); tempstream. close (); string JSON = getresponsestring (wresponse); wresponse. close (); // Delete the temporary file. delete (PATH); Return jsonconvert. deserializeobject <t> (JSON );}

2. Delete Baidu cloud Disk Files

// Rest @ Delete method public static string dodeletemethod (string _ OBJECT) {string uri = generateuri ("delete", _ OBJECT); httpwebrequest request = (httpwebrequest) webrequest. create (URI); Request. method = "delete"; request. contenttype = "application/JSON; charset = UTF-8"; request. useragent = "curl/7.19.7 (universal-apple-darwin10.0) libcurl/7.19.7 OpenSSL/0.9.8l zlib/1.2.3"; request. accept = "*/*"; request. contentlength = 0; using (httpwebresponse response = (httpwebresponse) request. getresponse () {using (streamreader reader = new streamreader (response. getresponsestream (), system. text. encoding. getencoding ("UTF-8") {return reader. readtoend ();}}}

3. Download Baidu cloud Disk Files

      public static string GET(string sobject)        {            string uri = GenerateUri("GET", sobject);            string _private = "&response-cache-control=private";            return uri + _private;        }

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.