標籤:des style blog http 使用 os io 檔案
圖1
圖2
圖3
圖4
1. 上傳百度雲端硬碟功能,由於百度開發人員中還沒有開放對.net
操作的SDK,所以我們現在只能使用原生的REST API
我們的做法就是如何用C# 語言調用 調用curl 命令。
2. curl是利用URL文法在命令列方式下工作的開源檔案傳輸工具。它被廣泛應用在Unix、多種Linux發行版中,並且有DOS和Win32、Win64下的移植版本.
要操作curl 我們需要引入LibCurlNet.dll
3.百度上傳我們需要有百度帳號,而且需要申請開發人員功能進入首頁後會有
AccessKey,Secrectkey 這兩個Key非常重要
4. 傳入參數擷取加密url,下面一部分代碼是把檔案寫入伺服器Temp下的一個臨時檔案。
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 + "/" + HttpUtility.UrlEncode(sobject) + "?sign=" + signture; string path = System.IO.Path.Combine(HttpContext.Current.Server.MapPath("~/Temp"), System.IO.Path.GetFileName(file.FileName)); Stream stream = file.InputStream; // 把 Stream 轉換成 byte[] byte[] bytes = new byte[stream.Length]; stream.Read(bytes, 0, bytes.Length); // 設定當前流的位置為流的開始 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 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(); //刪除臨時檔案 File.Delete(path); return code.ToString(); } catch (Exception ex) { throw new Exception("Error", ex); } }
5. 這個代碼就是調用LibCurlNet上傳的代碼。
6. 這個是Action代碼調用百度上傳Put後在把這個檔案名稱儲存到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); // 副檔名 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(); of.ObjectType = "Material"; if (".bmp,.jpg,.tiff,.gif,.pcx,.tga,.exif,.fpx,.svg,.psd,.cdr,.pcd,.dxf,.ufo,.eps,.ai,.raw".Contains(fileExtension)) { of.IsPic = true; } else { of.IsPic = false; } of.ObjectId = "M001";//Temp 值 of.FieldValue = sobject; int recNo = -1; if (viewModel.picturesList.Count > 0) { recNo = (viewModel.picturesList.Count + 1) * -1; } of.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.圖4 中Delete 功能現在只能刪除資料庫中的,而不能刪除 百度雲端硬碟中的,
刪除百度雲中的代碼還不知道怎麼實現,國內的資料太少了。
//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); //}
上傳百度雲第二中方法
1. 上面我們提調用百度雲介面需要加入libCurlNet.dll,這裡就不需要LibCurlNet.dll
2.百度上傳代碼
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 方法,帶傳送檔案 public static T doPutMethodToObj<T>(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(); //刪除臨時檔案 File.Delete(path); return JsonConvert.DeserializeObject<T>(json); }
2. 刪除百度雲端硬碟的的檔案
// REST @DELETE 方法 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. 下載百度雲端硬碟檔案
public static string GET(string sobject) { string uri = GenerateUri("GET", sobject); string _private = "&response-cache-control=private"; return uri + _private; }