首页 > 代码库 > 文件上传到百度云盘说明文档

文件上传到百度云盘说明文档

图1图1

图2图2

图3图3

图4图4

1. 上传百度云盘功能,由于百度开发者中还没有开放对.net

操作的SDK,所以我们现在只能使用原生的REST API

clip_image002

 

我们的做法就是如何用C# 语言调用 调用curl 命令。

2. curl是利用URL语法在命令行方式下工作的开源文件传输工具。它被广泛应用在Unix、多种Linux发行版中,并且有DOS和Win32、Win64下的移植版本.

要操作curl 我们需要引入LibCurlNet.dll

 clip_image003

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 = http://www.mamicode.com/sobject;>

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

clip_image003[1]

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 = http://www.mamicode.com/new Byte[ReadIn.Length]; // Read the file in 2 KB segments.>

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;        }