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;
|
}
|
}
|
|
|
}
|
}
|