开发者社区> 问答> 正文

图片上传

有没有c#图片上传的例子

    /// </summary>
        /// <param name="url"> url = "https://oapi.dingtalk.com/media/upload?access_token=" + token + "&type=image";</param>
        /// <param name="timeout"></param>
        /// <param name="fileBuffer">文件数据</param>
        /// <param name="fileName">文件名</param>
        public static string Post(string url, byte[] fileBuffer, String fileName)
        {//---------------------------1rlg4vnrodqg9f
            // type=file可以上传  type=image 为不合法的文件类型
            string boundary = "1rlg4vnrodqg9f"; //Microsoft.Owin.Security.Infrastructure.SecurityHelper.GenerateRadomStr();
            WebClient webClient = new WebClient();
            webClient.Headers.Add("Content-Type", string.Format("multipart/form-data; boundary={0}", boundary));
            string fileFormdataTemplate =
                            "\r\n--" + boundary +
                            "\r\nContent-Disposition:form-data;name=\"{0}\";filelength=\"{2}\";filename=\"{1}\"" +
                            "\r\nContent-Type:application/octet-stream" +
                            "\r\n\r\n";
            string formDataHeader = String.Format(fileFormdataTemplate, "media", fileName,fileBuffer.Length);
            byte[] formDataHeaderBuffer = Encoding.UTF8.GetBytes(formDataHeader);

            string begin = $"--{boundary}\r\n";
            byte[] beginBuffer = Encoding.UTF8.GetBytes(begin);

            string end = $"\r\n--{boundary}--\r\n";
            byte[] endBuffer = Encoding.UTF8.GetBytes(end); ;

            byte[] dataStream = new byte[formDataHeaderBuffer.Length + beginBuffer.Length + fileBuffer.Length + endBuffer.Length];
            formDataHeaderBuffer.CopyTo(dataStream, 0);
            beginBuffer.CopyTo(dataStream, formDataHeaderBuffer.Length);
            fileBuffer.CopyTo(dataStream, formDataHeaderBuffer.Length + begin.Length);
            endBuffer.CopyTo(dataStream, formDataHeaderBuffer.Length + begin.Length + fileBuffer.Length);
            var returnBuffer = webClient.UploadData(url, "POST", dataStream);
            Encoding encode = Encoding.UTF8;
            string resultJson = encode.GetString(returnBuffer);
            return resultJson;
        }

这个是看别人例子存在的问题。。。能不能加些c#的接口例子 ,,

展开
收起
luobenabc 2016-09-05 15:16:41 3006 0
3 条回答
写回答
取消 提交回答
  • Re图片上传
    我也碰到类似问题,请问楼主最后的代码解决另外这个问题吗?
    2016-09-06 15:40:08
    赞同 展开评论 打赏
  • Re图片上传
    .。。没找到啊。。。

    -------------------------

    Re图片上传
    。。自己挖坑自己解决 希望大家多贴点c#代码  
    c#服务端上传图片
      private static string HttpPostData(string url, string fileKeyName, string filePath, NameValueCollection stringDict)
            {
                string responseContent;
                var memStream = new MemoryStream();
                var webRequest = (HttpWebRequest)WebRequest.Create(url);
                // 边界符
                var boundary = "---------------" + DateTime.Now.Ticks.ToString("x");
                // 边界符
                var beginBoundary = Encoding.ASCII.GetBytes("--" + boundary + "\r\n");
                var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                // 最后的结束符
                var endBoundary = Encoding.ASCII.GetBytes("--" + boundary + "--\r\n");

                // 设置属性
                webRequest.Method = "POST";
                webRequest.ContentType = "multipart/form-data; boundary=" + boundary;

                // 写入文件
                const string filePartHeader =
                    "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n" +
                     "Content-Type: application/octet-stream\r\n\r\n";
                var header = string.Format(filePartHeader, fileKeyName, filePath);
                var headerbytes = Encoding.UTF8.GetBytes(header);

                memStream.Write(beginBoundary, 0, beginBoundary.Length);
                memStream.Write(headerbytes, 0, headerbytes.Length);

                var buffer = new byte[1024];
                int bytesRead; // =0

                while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                {
                    memStream.Write(buffer, 0, bytesRead);
                }

                // 写入字符串的Key
                var stringKeyHeader = "\r\n--" + boundary +
                                       "\r\nContent-Disposition: form-data; name=\"{0}\"" +
                                       "\r\n\r\n{1}\r\n";

                foreach (byte[] formitembytes in from string key in stringDict.Keys
                                                 select string.Format(stringKeyHeader, key, stringDict[key])
                                                     into formitem
                                                 select Encoding.UTF8.GetBytes(formitem))
                {
                    memStream.Write(formitembytes, 0, formitembytes.Length);
                }

                // 写入最后的结束边界符
                memStream.Write(endBoundary, 0, endBoundary.Length);

                webRequest.ContentLength = memStream.Length;

                var requestStream = webRequest.GetRequestStream();

                memStream.Position = 0;
                var tempBuffer = new byte[memStream.Length];
                memStream.Read(tempBuffer, 0, tempBuffer.Length);
                memStream.Close();

                requestStream.Write(tempBuffer, 0, tempBuffer.Length);
                requestStream.Close();

                var httpWebResponse = (HttpWebResponse)webRequest.GetResponse();

                using (var httpStreamReader = new StreamReader(httpWebResponse.GetResponseStream(), Encoding.GetEncoding("utf-8")))
                {
                    responseContent = httpStreamReader.ReadToEnd();
                }

                fileStream.Close();
                httpWebResponse.Close();
                webRequest.Abort();

                return responseContent;
            }
            public static PostImage uploadImage(string filePath)
            {
                string url = "https://oapi.dingtalk.com/media/upload?access_token=" + EnterpriseBusiness.GetToken().access_token + "&type=image";
                NameValueCollection nvc = new NameValueCollection();
                nvc["test"] = "test.jpg";
                var response = HttpPostData(url, "media", filePath, nvc);
                return JsonHelper<PostImage>.Deserialize(response);
          
            }
    2016-09-06 10:25:11
    赞同 展开评论 打赏
  • 您好,我们也会不断丰富例子,您也可以找论坛里其他人贴的C# demo来参考
    2016-09-05 19:53:34
    赞同 展开评论 打赏
问答分类:
问答地址:
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载