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

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

文件上传到百度云盘说明文档,布布扣,bubuko.com

时间: 2024-08-02 06:56:23

文件上传到百度云盘说明文档的相关文章

AjaxUpLoad.js使用实现文件上传

AjaxUpLoad.js的使用实现无刷新文件上传,如图. 图1 文件上传前图2 文件上传后 1.创建页面并编写HTML上传文档: <div class="uploadFile"> <span id="doc"><input type="text" disabled="disabled" /></span> <input type="hidden" id

用openoffice+jodconverter+webuploader+pdf.js实现文件上传、在线预览功能

一.背景 最近公司一个项目要实现一个文件上传以及多文档在线预览的功能,之前一直做无线工具开发的,没有涉及到这些东西.另外项目组缺java开发人员,而且自己也只是一个半吊子前端加小半吊子java开发人员,所以让我一个人先弄个Demo出来瞧瞧.在网上搜索了不少资料,在这里只是整理一下,留作以后查阅. 二.插件以及工具包 1.pdfjs-v1.7.225  前端pdf格式文件的显示组件 2.webuploader-0.1.5  百度的文件上传组件 3.video-js-6.2.5 html5视频播放组

[sharepoint]rest api文档库文件上传,下载,拷贝,剪切,删除文件,创建文件夹,修改文件夹属性,删除文件夹,获取文档列表

写在前面 最近对文档库的知识点进行了整理,也就有了这篇文章,当时查找这些接口,并用在实践中,确实废了一些功夫,也为了让更多的人走更少的弯路. 系列文章 sharepoint环境安装过程中几点需要注意的地方 Rest API的简单应用 rest api方式实现对文档库的管理 通过WebClient模拟post上传文件到服务器 WebHttpRequest在sharepoint文档库中的使用 [sharepoint]Rest api相关知识(转) [sharepoint]根据用户名获取该用户的权限

HTTP文件上传插件开发文档-JSP

版权所有 2009-2016 荆门泽优软件有限公司 保留所有权利 官方网站:http://www.ncmem.com/ 产品首页:http://www.ncmem.com/webplug/http-uploader/index.asp 在线演示:http://www.ncmem.com/products/http-uploader2/index.asp, 开发文档:asp,jsp,php,asp.net, 升级日志:http://www.cnblogs.com/xproer/archive/20

带进度的多文件上传(支持上传.doc后缀的word文档并在线预览)

原文:带进度的多文件上传(支持上传.doc后缀的word文档并在线预览) 源代码下载地址:http://www.zuidaima.com/share/1550463556848640.htm 演示地址:http://img.zeroteam.net/     访问路径和自己工程的设置有关 如:http://localhost:8081/strutd2_fileupload/index.jsp

Spring 4 官方文档学习(十一)Web MVC 框架之multipart(文件上传)支持

http://docs.spring.io/spring/docs/current/spring-framework-reference/html/mvc.html#mvc-multipart 1.简介 Spring内置的multipart支持会处理web应用中的文件上传.你可以启用该支持 -- 通过可插拔的MultipartResolver对象们,它们都是定义在 org.springframework.web.multipart 包中.Spring提供了一个MultipartResolver实

ajax结合文件上传类进行多文件的单个上传

今天做项目的时候碰见一个问题:之前一个同事离职之前做了一个网站,有一个上传商品详细图片的功能,当时已经完成,但是由于后期程序的有更改以及更改的程序员的水平也是参差不齐,最后导致程序bug很多,由于当时用的是一个框架,最终也没找到说明文档,后来我就重新写了一个结合ajax上传文件的upload.classs.php虽然界面欠缺美观,但是通俗易懂好维护. //首先是页面. index.php <!DOCTYPE html> <html lang="en"> <

文件上传利器JQuery上传插件Uploadify

在做日常项目中,经常在后台需要上传图片等资源文件,之前使用过几次这个组件,感觉非常好用 ,但是每次使用的时候都是需要经过一番查阅,所以还不如记住在这里,以后使用的时候就翻翻. 他的官方网站如下:http://www.uploadify.com/ 插件下载地址:http://www.uploadify.com/download 说明文档:http://www.uploadify.com/documentation 在此之前,先说明下插件使用流程,该插件是基于jQuery的,所以我们在使用之前需要引

ASP.NET实战之文件上传

时下比较流行的云盘,比如百度云盘,360云盘,金山快盘等等,相信大家都用过.云盘是互联网存储工具,是互联网云技术的产物,是通过互联网为企业和个人提供数据信息的存储,读取以及下载等服务,其最大的两个特点是安全稳定和海量存储.我的笔记本硬盘只有500G,有一天当我发现我的6个硬盘分区中红了4个,我就开始往我的百度云盘上"搬东西",这个搬东西就是我们今天要谈到的"文件上传". 其实文件上传在互联网应用和网站开发中十分常见,我们在各类社交软件中使用的"照片上传&q