标签:des style blog http 使用 os io 文件
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; }
标签:des style blog http 使用 os io 文件
原文地址:http://www.cnblogs.com/json_Chen/p/3920434.html