lixiaojun
2023-03-20 14801a2e40bc79833c41151a37fe4cb0acbc5c7f
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
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using IStation.Bimface;
 
namespace IStation
{
    /// <summary>
    /// 文件上传
    /// </summary>
    public sealed partial class BimfaceClient
    {
        private const string _normalUploadUrl = @"https://file.bimface.com/upload";//普通文件流上传URL
        private const string _policyUploadUrl = @"https://file.bimface.com/upload/policy";//文件直传URL
 
 
        /// <summary>
        /// 普通文件流上传(不推荐)
        /// </summary>
        /// <param name="fullFileName">文件全路径</param>
        public UploadFileResponse UploadFileGeneral(string fullFileName, string fileName = null)
        {
            GetAccessToken();
            if (string.IsNullOrEmpty(fileName))
            {
                var fileInfo = new FileInfo(fullFileName);
                fileName = fileInfo.Name;
            }
            var utf8_fileName = Encoding.UTF8.GetString(Encoding.UTF8.GetBytes(fileName));
            var url = string.Format("{0}?name={1}", _normalUploadUrl, utf8_fileName);
            var request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = WebRequestMethods.Http.Put;
            var autoHeader = new HttpHeaders().GetBasicAuthorHeader(_accesstoken);
            request.Headers.Add(autoHeader.Key, autoHeader.Value);
            byte[] bytes;
            using (FileStream steam = new FileStream(fullFileName, FileMode.Open, FileAccess.Read))
            {
                bytes = new byte[(int)steam.Length];
                steam.Read(bytes, 0, bytes.Length);
            }
            request.ContentLength = bytes.Length;
            request.AllowWriteStreamBuffering = true;
            using (Stream stream = request.GetRequestStream())
            {
                stream.Write(bytes, 0, bytes.Length);
                stream.Flush();
            }
            var response = request.GetResponse();
            string responsetext = string.Empty;
            using (Stream stream = response.GetResponseStream())
            using (StreamReader reader = new StreamReader(stream))
            {
                responsetext = reader.ReadToEnd();
            }
            var result = JsonHelper.Json2Object<Result<UploadFileResponse>>(responsetext);
            if (result.code != Constants.Success)
            {
                throw new BimfaceException(result.code);
            }
            if (result.data.status != Constants.Success)
            {
                throw new BimfaceException(result.code);
            }
            return result.data;
        }
 
        /// <summary>
        /// 普通文件流上传Core(不推荐)
        /// </summary>
        /// <param name="fullFileName">文件全路径</param>
        public UploadFileResponse UploadFileGeneralCore(string fullFileName, string fileName = null)
        {
            GetAccessToken();
            if (string.IsNullOrEmpty(fileName))
            {
                var fileInfo = new FileInfo(fullFileName);
                fileName = fileInfo.Name;
            }
            var utf8_fileName = Encoding.UTF8.GetString(Encoding.UTF8.GetBytes(fileName));
            var url = string.Format("{0}?name={1}", _normalUploadUrl, utf8_fileName);
            using (var httpClient = new HttpClient())
            using (var request=new HttpRequestMessage(HttpMethod.Put,url))
            using (var stream= new FileStream(fullFileName, FileMode.Open, FileAccess.Read))
            {
                var autoHeader = new HttpHeaders().GetBasicAuthorHeader(_accesstoken);
                request.Headers.Add(autoHeader.Key, autoHeader.Value);
                request.Content = new StreamContent(stream);
                var response = httpClient.SendAsync(request).Result;
                response.EnsureSuccessStatusCode();
                var responsetext=response.Content.ReadAsStringAsync().Result;
                var result = JsonHelper.Json2Object<Result<UploadFileResponse>>(responsetext);
                if (result.code != Constants.Success)
                {
                    throw new BimfaceException(result.code);
                }
                if (result.data.status != Constants.Success)
                {
                    throw new BimfaceException(result.code);
                }
                return result.data;
            }
        }
 
        /// <summary>
        /// 文件直传(推荐)
        /// </summary>
        /// <param name="fullFileName">文件全路径</param>
        /// <param name="fileName">文件名称(必须带后缀)</param>
        public UploadFileResponse UploadFilePolicy(string fullFileName, string fileName = null)
        {
            if (string.IsNullOrEmpty(fileName))
            {
                var fileInfo = new FileInfo(fullFileName);
                fileName = fileInfo.Name;
            }
            var policyResult = GetFileUploadPolicy(fileName);
            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 textFormTemplate = "Content-Disposition: form-data; name=\"{0}\"\r\n\r\n" + "{1}\r\n";//文本模板
            var fileFormTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n" + "Content-Type: application/octet-stream\r\n\r\n";//文件模板
 
            var dic = new Dictionary<string, string>();
            dic.Add("name", fileName);
            dic.Add("key", policyResult.objectKey);
            dic.Add("policy", policyResult.policy);
            dic.Add("OSSAccessKeyId", policyResult.accessId);
            dic.Add("success_action_status", "200");
            dic.Add("callback", policyResult.callbackBody);
            dic.Add("signature", policyResult.signature);
 
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(policyResult.host);
            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 textBytesList = dic.Select(x =>
            {
                var textFormItem = string.Format(textFormTemplate, x.Key, x.Value);
                byte[] textFormItemBytes = Encoding.UTF8.GetBytes(textFormItem);
                contentLength += beginBoundaryBytes.Length;
                contentLength += textFormItemBytes.Length;
                return textFormItemBytes;
            }).ToList();
 
            var fileFormItem = string.Format(fileFormTemplate, "file", fileName);
            byte[] fileFormItemBytes = Encoding.UTF8.GetBytes(fileFormItem);
            contentLength += beginBoundaryBytes.Length;
            contentLength += fileFormItemBytes.Length;
 
            var fileStream = new FileStream(fullFileName, FileMode.Open, FileAccess.Read);
            contentLength += fileStream.Length;
            contentLength += endBoundaryBytes.Length;
            request.ContentLength = contentLength;
            var requestStream = request.GetRequestStream();
            textBytesList.ForEach(x =>
            {
                requestStream.Write(beginBoundaryBytes, 0, beginBoundaryBytes.Length);
                requestStream.Write(x, 0, x.Length);
            });
            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();
            }
 
            var result = JsonHelper.Json2Object<Result<UploadFileResponse>>(responsetext);
            if (result.code != Constants.Success)
            {
                throw new BimfaceException(result.code);
            }
            if (result.data.status != Constants.Success)
            {
                throw new BimfaceException(result.code);
            }
 
            return result.data;
        }
 
        /// <summary>
        /// 文件直传Core(推荐)
        /// </summary>
        /// <param name="fullFileName">文件全路径</param>
        /// <param name="fileName">文件名称(必须带后缀)</param>
        public UploadFileResponse UploadFilePolicyCore(string fullFileName, string fileName = null)
        {
            if (string.IsNullOrEmpty(fileName))
            {
                var fileInfo = new FileInfo(fullFileName);
                fileName = fileInfo.Name;
            }
            var policyResult = GetFileUploadPolicy(fileName);
            string responsetext = string.Empty;
            using (var httpClient = new HttpClient())
            {
                httpClient.Timeout = Timeout.InfiniteTimeSpan;
                var url = policyResult.host;
                var content = new MultipartFormDataContent();
                content.Add(new StringContent(fileName),"name");
                content.Add(new StringContent(policyResult.objectKey), "key");
                content.Add(new StringContent(policyResult.policy), "policy");
                content.Add(new StringContent(policyResult.accessId), "OSSAccessKeyId");
                content.Add(new StringContent("200"), "success_action_status");
                content.Add(new StringContent(policyResult.callbackBody), "callback");
                content.Add(new StringContent(policyResult.signature), "signature");
                using (var fileStream = new FileStream(fullFileName, FileMode.Open, FileAccess.Read))
                using (var streamContent = new StreamContent(fileStream, 2048))
                {
                    content.Add(streamContent,"file",fileName);
                    var response = httpClient.PostAsync(url,content).Result;
                    response.EnsureSuccessStatusCode();
                    responsetext = response.Content.ReadAsStringAsync().Result;
                }
            }
            var result = JsonHelper.Json2Object<Result<UploadFileResponse>>(responsetext);
            if (result.code != Constants.Success)
            {
                throw new BimfaceException(result.code);
            }
            if (result.data.status != Constants.Success)
            {
                throw new BimfaceException(result.code);
            }
 
            return result.data;
        }
 
        /// <summary>
        /// 文件直传
        /// </summary>
        /// <param name="fullFileName"></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public long UploadFilePolicyEx(string fullFileName, string fileName = null)
        {
            var response = UploadFilePolicy(fullFileName,fileName);
            if (response.status != Constants.Success)
            {
                return 0;
            }
            return response.fileId.Value;
        }
 
        //获取文件直传Policy
        private UploadFilePolicyResponse GetFileUploadPolicy(string fileName)
        {
            GetAccessToken();
            var utf8_fileName = Encoding.UTF8.GetString(Encoding.UTF8.GetBytes(fileName));
            var url = string.Format("{0}?name={1}", _policyUploadUrl, utf8_fileName);
            using (var httpClient = new HttpClient())
            using (var request = new HttpRequestMessage(HttpMethod.Get, _translateUrl))
            {
                var autoHeader = new HttpHeaders().GetBasicAuthorHeader(_accesstoken);
                request.Headers.Add(autoHeader.Key, autoHeader.Value);
                var response = httpClient.SendAsync(request).Result;
                response.EnsureSuccessStatusCode();
                var responsetext = response.Content.ReadAsStringAsync().Result;
                var result = JsonHelper.Json2Object<Result<UploadFilePolicyResponse>>(responsetext);
                if (result.code != Constants.Success)
                {
                    throw new BimfaceException(result.code);
                }
                return result.data;
            }
        }
 
 
    }
}