lixiaojun
2022-07-27 96887ec041ba8ddb170c75c1492fc210735ecb37
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
 
namespace IStation.Untity 
{
    /// <summary>
    /// http文件辅助类
    /// </summary>
    public class HttpFileHelper
    {
        /// <summary>
        /// 上传文件
        /// </summary>
        public static string Upload(string url, string filePath)
        {
            if (string.IsNullOrEmpty(url))
                return default;
            if (string.IsNullOrEmpty(filePath))
                return default;
            if (!System.IO.File.Exists(filePath))
                return default;
            try
            {
                var fileInfo = new System.IO.FileInfo(filePath);
                string boundary = "----" + DateTime.Now.Ticks.ToString("x");// 边界符
                byte[] beginBoundaryBytes = Encoding.UTF8.GetBytes("--" + boundary + "\r\n");     // 边界符开始。【☆】右侧必须要有 \r\n 。
                byte[] endBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n"); // 边界符结束。【☆】两侧必须要有 --\r\n 。
 
                var fileFormTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n" + "Content-Type: application/octet-stream\r\n\r\n";//文件模板
 
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.ContentType = string.Format("multipart/form-data; boundary={0}", boundary);
                request.Method = WebRequestMethods.Http.Post;
                request.AllowWriteStreamBuffering = false;
                //request.KeepAlive = true;
                request.Timeout = -1;
 
                long contentLength = 0;
 
                var fileFormItem = string.Format(fileFormTemplate, "file", fileInfo.Extension);
                byte[] fileFormItemBytes = Encoding.UTF8.GetBytes(fileFormItem);
                contentLength += beginBoundaryBytes.Length;
                contentLength += fileFormItemBytes.Length;
 
                var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                contentLength += fileStream.Length;
                contentLength += endBoundaryBytes.Length;
                request.ContentLength = contentLength;
                var requestStream = request.GetRequestStream();
                requestStream.Write(beginBoundaryBytes, 0, beginBoundaryBytes.Length);
                requestStream.Write(fileFormItemBytes, 0, fileFormItemBytes.Length);
 
                //每次上传4M
                byte[] buffer = new Byte[checked((uint)Math.Min(4096, (int)fileStream.Length))];
                int bytesRead = 0;
                while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
                {
                    requestStream.Write(buffer, 0, bytesRead);
                }
                requestStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
 
                fileStream.Close();
                requestStream.Close();
 
                var response = request.GetResponse();
                string responsetext = string.Empty;
                using (Stream stream = response.GetResponseStream())
                using (StreamReader reader = new StreamReader(stream))
                {
                    responsetext = reader.ReadToEnd();
                }
                return responsetext;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
 
        /// <summary>
        /// 文件上传
        /// </summary>
        public static string Upload(string url, Stream stream, string suffix)
        {
            if (string.IsNullOrEmpty(url))
                return default;
            if (stream == null)
                return default;
            try
            {
                string boundary = "----" + DateTime.Now.Ticks.ToString("x");// 边界符
                byte[] beginBoundaryBytes = Encoding.UTF8.GetBytes("--" + boundary + "\r\n");     // 边界符开始。【☆】右侧必须要有 \r\n 。
                byte[] endBoundaryBytes = Encoding.UTF8.GetBytes("\r\n--" + boundary + "--\r\n"); // 边界符结束。【☆】两侧必须要有 --\r\n 。
 
                var fileFormTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n" + "Content-Type: application/octet-stream\r\n\r\n";//文件模板
 
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
                request.ContentType = string.Format("multipart/form-data; boundary={0}", boundary);
                request.Method = WebRequestMethods.Http.Post;
                request.AllowWriteStreamBuffering = false;
                //request.KeepAlive = true;
                request.Timeout = -1;
 
                long contentLength = 0;
 
                var fileFormItem = string.Format(fileFormTemplate, "file", suffix);
                byte[] fileFormItemBytes = Encoding.UTF8.GetBytes(fileFormItem);
 
                contentLength += beginBoundaryBytes.Length;
                contentLength += fileFormItemBytes.Length;
                //var fileStream = new FileStream(steam, FileMode.Open, FileAccess.Read);
 
                contentLength += stream.Length;
                contentLength += endBoundaryBytes.Length;
                request.ContentLength = contentLength;
                var requestStream = request.GetRequestStream();
                requestStream.Write(beginBoundaryBytes, 0, beginBoundaryBytes.Length);
                requestStream.Write(fileFormItemBytes, 0, fileFormItemBytes.Length);
 
                //每次上传4M
                byte[] buffer = new Byte[checked((uint)Math.Min(4096, (int)stream.Length))];
                int bytesRead = 0;
                while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) != 0)
                {
                    requestStream.Write(buffer, 0, bytesRead);
                }
                requestStream.Write(endBoundaryBytes, 0, endBoundaryBytes.Length);
 
                stream.Close();
                requestStream.Close();
 
                var response = request.GetResponse();
                string responsetext = string.Empty;
                using (Stream rs = response.GetResponseStream())
                using (StreamReader reader = new StreamReader(rs))
                {
                    responsetext = reader.ReadToEnd();
                }
                return responsetext;
            }
            catch (System.Exception ex)
            {
                throw ex;
            }
 
        }
 
        /// <summary>
        /// 下载文件
        /// </summary>
        public static Stream Download(string url)
        {
            var request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "GET";
            request.ContentType = "application/json";
            //request.Timeout = 10 * 1000;//请求超时时间      
            using (var response = (HttpWebResponse)request.GetResponse())
            {
                if (response.StatusCode == HttpStatusCode.NoContent)
                    return null;
                var ms = new MemoryStream();
                response.GetResponseStream().CopyTo(ms);
                return ms;
            }
        }
 
        /// <summary>
        /// 下载文件
        /// </summary>
        public static void DownloadUri(string uri, string filePath)
        {
            var client = new System.Net.WebClient();
            client.DownloadFile(uri, filePath);
        }
         
    }
}