Пример #1
0
 /// <summary>
 /// 异步上传文件
 /// </summary>
 /// <param name="param"></param>
 /// <returns></returns>
 public static async Task <string> UploadFileAsync(HttpClientUpload param)
 {
     return(await Task.Run(() => { return UploadFile(param); }));
 }
Пример #2
0
        /// <summary>
        /// 上传文件
        /// </summary>
        /// <param name="param"></param>
        /// <returns></returns>
        public static string UploadFile(HttpClientUpload param)
        {
            var rq = (HttpWebRequest)WebRequest.Create(param.Url);

            rq.Method = "POST";
            //rq.UserAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.57 Safari/537.36";
            var    fileMemoryStream = new MemoryStream(); //文件写入流
            string boundary         = "---------------------" + DateTime.Now.Ticks.ToString("x", NumberFormatInfo.InvariantInfo);

            rq.ContentType = $"multipart/form-data; boundary={boundary}";

            if (param.Files != null && param.Files.Count > 0)
            {
                param.Files.ForEach(files =>
                {
                    var postStream = new MemoryStream();
                    //读取文件流
                    if (string.IsNullOrWhiteSpace(files.FileName))
                    {
                        files.FileName = Path.GetFileName(files.FilePath);
                    }

                    var fileStream = new FileStream(files.FilePath, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);

                    StringBuilder fileFormdataTemplate = new StringBuilder();
                    fileFormdataTemplate.Append("--" + boundary + "\r\n");
                    fileFormdataTemplate.Append("Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n");
                    fileFormdataTemplate.Append("Content-Type: application/octet-stream\r\n\r\n");

                    var formHeader = string.Format(fileFormdataTemplate.ToString(), files.Name, files.FileName);

                    //头部边界线
                    var formHeaderBytes = Encoding.UTF8.GetBytes(formHeader);

                    //写入头部边界线
                    postStream.Write(formHeaderBytes, 0, formHeaderBytes.Length);

                    //写入文件内存流
                    if (fileStream != null)
                    {
                        byte[] fileBuffer = new byte[1024];
                        int filebytesRead = 0;
                        while ((filebytesRead = fileStream.Read(fileBuffer, 0, fileBuffer.Length)) != 0)
                        {
                            postStream.Write(fileBuffer, 0, filebytesRead);
                        }
                    }

                    //文件换行
                    var fileLine = Encoding.UTF8.GetBytes("\r\n");
                    postStream.Write(fileLine, 0, fileLine.Length);

                    //写入到总流
                    fileMemoryStream.Write(postStream.ToArray(), 0, postStream.ToArray().Length);

                    postStream.Close();
                    postStream.Dispose();
                });
            }

            //边界线
            var footer = Encoding.ASCII.GetBytes("--" + boundary + "--\r\n");

            fileMemoryStream.Write(footer, 0, footer.Length);

            var data = fileMemoryStream.ToArray();

            rq.ContentLength = data.Length;

            //写入流
            using (Stream requestStream = rq.GetRequestStream())
            {
                requestStream.Write(data, 0, data.Length);
            }
            var response = (HttpWebResponse)rq.GetResponse();

            using (var responseStream = response.GetResponseStream())
            {
                using (var myStreamReader = new StreamReader(responseStream, Encoding.GetEncoding("utf-8")))
                {
                    return(myStreamReader.ReadToEnd());
                }
            }
        }