• WebClient multipart/form-data 文件上传


     public class HttpRequestClient
        {
            private ArrayList bytesArray;
            private Encoding encoding = Encoding.UTF8;
            private string boundary = String.Empty;
    
            public HttpRequestClient()
            {
                bytesArray = new ArrayList();
                string flag = DateTime.Now.Ticks.ToString("x");
                boundary = "---------------------------" + flag;
            }
    
            /// <summary>
            /// 合并请求数据
            /// </summary>
            /// <returns></returns>
            private byte[] MergeContent()
            {
                int length = 0;
                int readLength = 0;
                string endBoundary = "--" + boundary + "--
    ";
                byte[] endBoundaryBytes = encoding.GetBytes(endBoundary);
    
                bytesArray.Add(endBoundaryBytes);
    
                foreach (byte[] b in bytesArray)
                {
                    length += b.Length;
                }
    
                byte[] bytes = new byte[length];
    
                foreach (byte[] b in bytesArray)
                {
                    b.CopyTo(bytes, readLength);
                    readLength += b.Length;
                }
    
                return bytes;
            }
    
            /// <summary>
            /// 上传
            /// </summary>
            /// <param name="requestUrl">请求url</param>
            /// <param name="responseText">响应</param>
            /// <returns></returns>
            public bool Upload(String requestUrl, out String responseText)
            {
                WebClient webClient = new WebClient();
                webClient.Headers.Add("Content-Type", "multipart/form-data; boundary=" + boundary);
                responseText = string.Empty;
                byte[] responseBytes;
                byte[] bytes = MergeContent();
    
                try
                {
                    //responseText = requestUrl;//+ "requestUrl---   "    + bytes == null ? "error null" : bytes.Length.ToString();
                    //return true;
                    responseBytes = webClient.UploadData(requestUrl, bytes);
    
                    responseText = System.Text.Encoding.UTF8.GetString(responseBytes);
    
                }
                catch (Exception ex)
                {
                    throw ex;
                    //responseText = ex.Message;
                    //return false;
                    //Stream responseStream = ex.Response.GetResponseStream();
                    //responseBytes = new byte[ex.Response.ContentLength];
                    //responseStream.Read(responseBytes, 0, responseBytes.Length);
                }
                responseText = System.Text.Encoding.UTF8.GetString(responseBytes);
                return false;
            }
    
            /// <summary>
            /// 设置表单数据字段
            /// </summary>
            /// <param name="fieldName">字段名</param>
            /// <param name="fieldValue">字段值</param>
            /// <returns></returns>
            public void SetFieldValue(String fieldName, String fieldValue)
            {
                string httpRow = "--" + boundary + "
    Content-Disposition: form-data; name="{0}"
    
    {1}
    ";
                string httpRowData = String.Format(httpRow, fieldName, fieldValue);
    
                bytesArray.Add(encoding.GetBytes(httpRowData));
            }
    
            /// <summary>
            /// 设置表单文件数据
            /// </summary>
            /// <param name="fieldName">字段名</param>
            /// <param name="filename">字段值</param>
            /// <param name="contentType">内容内型</param>
            /// <param name="fileBytes">文件字节流</param>
            /// <returns></returns>
            public void SetFieldValue(String fieldName, String filename, String contentType, Byte[] fileBytes)
            {
                string end = "
    ";
                string httpRow = "--" + boundary + "
    Content-Disposition: form-data; name="{0}"; filename="{1}"
    Content-Type: {2}
    
    ";
                string httpRowData = String.Format(httpRow, fieldName, filename, contentType);
    
                byte[] headerBytes = encoding.GetBytes(httpRowData);
                byte[] endBytes = encoding.GetBytes(end);
                byte[] fileDataBytes = new byte[headerBytes.Length + fileBytes.Length + endBytes.Length];
    
                headerBytes.CopyTo(fileDataBytes, 0);
                fileBytes.CopyTo(fileDataBytes, headerBytes.Length);
                endBytes.CopyTo(fileDataBytes, headerBytes.Length + fileBytes.Length);
    
                bytesArray.Add(fileDataBytes);
            }
        }
            /// <summary>
            /// 上传图片 返回空上传失败
            /// </summary>
            /// <param name="posturl"></param>
            /// <param name="userid"></param>
            /// <param name="filename"></param>
            /// <param name="dir"></param>
            /// <param name="data"></param>
            /// <returns></returns>
            public static string UpLoadFile(string posturl, int userid, string filename, string dir, byte[] data)
            {
                string result = string.Empty; 
                try
                { 
                    var httpRequestClient = new HttpRequestClient();
    
                    httpRequestClient.SetFieldValue("userId", userid.ToString());
                    httpRequestClient.SetFieldValue("upFile", filename, "application/octet-stream", data);
                    httpRequestClient.SetFieldValue("dir", dir);
    
    
                    httpRequestClient.Upload(posturl, out result);
                    //return result;
                    UploadImg img = Newtonsoft.Json.JsonConvert.DeserializeObject<UploadImg>(result);
    
                    if (img.state.ToUpper() == "SUCCESS")
                    {
                        return ConfigHelper.GetImageDomain() + img.url;
                        //imgUrlList.Add("http://img.zhijia.com" + uploadResult.url);
                        // imgUrlList.Add(WebConfig.ImgLink + uploadResult.url);
                    }
                    return result;
                }
                catch (Exception ex)
                {
                    throw ex;
                    //return "error:" + JsonConvert.SerializeObject(ex) + result;
                    //return string.Empty;
                }
                //  img.state=
            }
             string files = request.Head;    //用户头像
                    if (Request.Files != null && Request.Files.Count() > 0)
                    {
                        var reqFile = Request.Files[0];
                        var fileBytes = new byte[reqFile.ContentLength];
                        reqFile.InputStream.Read(fileBytes, 0, (int)reqFile.ContentLength);
                        var fileName = RequestInfo.UserId + reqFile.FileName; //+ AppApi.Helper.Function.GetExtensionName(fileBytes);
    
                        files = AppApi.Helper.Function.UpLoadFile(AppApi.Helper.ConfigHelper.GetImageFileService(), RequestInfo.UserId, fileName, AppApi.Helper.ConfigHelper.GetHeadDIR(), fileBytes);
                    }

    此随笔或为自己所写、或为转载于网络。仅用于个人收集及备忘。

  • 相关阅读:
    大一训练赛20181105-二分三分分治部分
    该说命运弄人,毫不留情。
    矩阵快速幂模板
    Final Destination II -- 矩阵快速幂模板题
    UVA -580 组合数学
    NYOJ-16-矩形嵌套 记忆化搜索
    封装标签省,市,县。三级联动
    java压缩图片设置宽高
    sql分页
    常用的正则表达式@java后台
  • 原文地址:https://www.cnblogs.com/shy1766IT/p/15421877.html
Copyright © 2020-2023  润新知