C#開發BIMFACE系列4 服務端API之源上傳文件

在註冊成爲BIMFACE的應用開發者後,要能在瀏覽器裏瀏覽你的模型或者獲取你模型內的BIM數據, 首先須要把你的模型文件上傳到BIMFACE。根據不一樣場景,BIMFACE提供了豐富的文件相關的接口。html

文件相關全部接口都須要提供有效的Access token。不支持View token。 web

方式一:普通文件流上傳
請求地址:PUT https://file.bimface.com/upload
說明:使用普通文件流上傳,不支持表單方式;文件流須要在request body中傳遞。
參數:

內容類型(ContentType):application/octet-streamjson

請求Path:https://file.bimface.com/upload?name=3F.rvt數組

請求Header:"Authorization: Bearer dc671840-bacc-4dc5-a134-97c1918d664b"。JSON格式。

請求體須要上傳的文件流。瀏覽器

HTTP 響應示例app

{
  "code" : "success",
  "data" : {
    "createTime" : "2017-11-09 13:25:03",
    "etag" : "19349858cjs98ericu989",
    "fileId" : 1216113551663296,
    "length" : 39044,
    "name" : "-1F.rvt",
    "status" : "success",
    "suffix" : "rvt"
  },
  "message" : ""
}

C#實現方法ide

 1 /// <summary>
 2 ///  普通文件流上傳【不推薦使用該方式。推薦使用文件直傳 UploadFileByPolicy()方法】
 3 /// </summary>
 4 /// <param name="accessToken">令牌</param>
 5 /// <param name="fileName">【必填】文件的名稱(不包含路徑)</param>
 6 /// <param name="fileStream">文件流</param>
 7 /// <param name="sourceId">【可選】調用方的文件源ID,不能重複</param>
 8 /// <returns></returns>
 9 public virtual FileUploadResponse UploadFileByStream(string accessToken, string fileName, Stream fileStream, string sourceId = "")
10 {
11     /* 重要提示:使用普通文件流上傳,不支持表單方式; 文件流須要在 request body 中傳遞 */
12 
13     //PUT 方式。例如:https://file.bimface.com/upload?name=3F.rvt
14     string url = string.Format(BimfaceConstants.FILE_HOST + "/upload?name={0}", fileName.UrlEncode(Encoding.UTF8));  //文件的全名,使用URL編碼(UTF-8),最多256個字符
15     if (sourceId.IsNotNullAndWhiteSpace())
16     {
17         url = url + "&sourceId=" + sourceId;
18     }
19 
20     byte[] fileBytes = fileStream.ToByteArray();
21 
22     BimFaceHttpHeaders headers = new BimFaceHttpHeaders();
23     headers.AddOAuth2Header(accessToken);
24 
25     try
26     {
27         FileUploadResponse response;
28 
29         HttpManager httpManager = new HttpManager(headers);
30         HttpResult httpResult = httpManager.UploadData(url, fileBytes, WebRequestMethods.Http.Put);
31         if (httpResult.Status == HttpResult.STATUS_SUCCESS)
32         {
33             response = httpResult.Text.DeserializeJsonToObject<FileUploadResponse>();
34         }
35         else
36         {
37             response = new FileUploadResponse
38             {
39                 Message = httpResult.RefText
40             };
41         }
42 
43         return response;
44     }
45     catch (Exception ex)
46     {
47         throw new Exception("普通文件流上時發生異常!", ex);
48     }
49 }

 其中引用的 httpManager.UploadData() 方法以下:編碼

 1 /// <summary>
 2 ///  將數據緩衝區(通常是指文件流或內存流對應的字節數組)上載到由 URI 標識的資源。(包含body數據)
 3 /// </summary>
 4 /// <param name="url">請求目標URL</param>
 5 /// <param name="data">主體數據(字節數據)。若是沒有請傳遞null</param>
 6 /// <param name="method">請求的方法。請使用 WebRequestMethods.Http 的枚舉值</param>
 7 /// <param name="contentType"><see langword="Content-type" /> HTTP 標頭的值。請使用 ContentType 類的常量來獲取。默認爲 application/octet-stream</param>
 8 /// <returns>HTTP-POST的響應結果</returns>
 9 public HttpResult UploadData(string url, byte[] data, string method = WebRequestMethods.Http.Post, string contentType = HttpContentType.APPLICATION_OCTET_STREAM)
10 {
11     return RequestData(url, data, method, contentType);
12 }
 1 /// <summary>
 2 ///  將數據緩衝區(通常是指文件流或內存流對應的字節數組)上載到由 URI 標識的資源。(包含body數據)
 3 /// </summary>
 4 /// <param name="url">請求目標URL</param>
 5 /// <param name="data">主體數據(字節數據)。若是沒有請傳遞null</param>
 6 /// <param name="method">請求的方法。請使用 WebRequestMethods.Http 的枚舉值</param>
 7 /// <param name="contentType"><see langword="Content-type" /> HTTP 標頭的值。請使用 ContentType 類的常量來獲取。默認爲 application/octet-stream</param>
 8 /// <returns>HTTP-POST的響應結果</returns>
 9 private HttpResult RequestData(string url, byte[] data, string method = WebRequestMethods.Http.Post, string contentType = HttpContentType.APPLICATION_OCTET_STREAM)
10 {
11     HttpResult httpResult = new HttpResult();
12     HttpWebRequest httpWebRequest = null;
13 
14     try
15     {
16         httpWebRequest = WebRequest.Create(url) as HttpWebRequest;
17         httpWebRequest.Method = method;
18         httpWebRequest.Headers = HeaderCollection;
19         httpWebRequest.CookieContainer = CookieContainer;
20         httpWebRequest.ContentType = contentType;
21         httpWebRequest.UserAgent = _userAgent;
22         httpWebRequest.AllowAutoRedirect = _allowAutoRedirect;
23         httpWebRequest.ServicePoint.Expect100Continue = false;
24 
25         if (data != null)
26         {
27             httpWebRequest.AllowWriteStreamBuffering = true;
28             httpWebRequest.ContentLength = data.Length;
29 
30             using (Stream requestStream = httpWebRequest.GetRequestStream())
31             {
32                 requestStream.Write(data, 0, data.Length);
33                 requestStream.Flush();
34             }
35         }
36 
37         HttpWebResponse httpWebResponse = httpWebRequest.GetResponse() as HttpWebResponse;
38         if (httpWebResponse != null)
39         {
40             GetResponse(ref httpResult, httpWebResponse);
41             httpWebResponse.Close();
42         }
43     }
44     catch (WebException webException)
45     {
46         GetWebExceptionResponse(ref httpResult, webException);
47     }
48     catch (Exception ex)
49     {
50         GetExceptionResponse(ref httpResult, ex, method, contentType);
51     }
52     finally
53     {
54         if (httpWebRequest != null)
55         {
56             httpWebRequest.Abort();
57         }
58     }
59 
60     return httpResult;
61 }
View Code
方式二:指定外部文件url方式上傳
若是須要上傳的文件不在本地,且該文件能夠經過指定的HTTP URL能夠下載,BIMFACE支持直接傳一個外部的HTTP文件URL, BIMFACE會去下載該文件,而無須用戶先下載,再上傳。
請求地址:PUT https://file.bimface.com/upload
說明:BIMFACE支持直接傳一個外部的HTTP文件URL, BIMFACE會去下載該文件,而無須用戶先下載,再上傳。
參數:

內容類型(ContentType):application/jsonurl

請求Path:https://file.bimface.com/upload?name=example.rvt&url=http(s)://xxxxxxxxxxxspa

請求Header:"Authorization: Bearer dc671840-bacc-4dc5-a134-97c1918d664b"。JSON格式。

請求體須要上傳的文件流。

HTTP 響應示例

{
  "code" : "success",
  "data" : {
    "createTime" : "2017-11-09 13:25:03",
    "etag" : "19349858cjs98ericu989",
    "fileId" : 1216113551663296,
    "length" : 39044,
    "name" : "-1F.rvt",
    "status" : "success",
    "suffix" : "rvt"
  },
  "message" : ""
}

C#實現方法

 1 /// <summary>
 2 ///  指定外部文件url方式上傳文件
 3 /// </summary>
 4 /// <param name="accessToken">令牌</param>
 5 /// <param name="fileName">【必填】文件的全名</param>
 6 /// <param name="fileUrl">【必填】文件所在url</param>
 7 /// <param name="sourceId">【可選】調用方的文件源ID,不能重複</param>
 8 /// <param name="etag">【可選】文件etag</param>
 9 /// <returns></returns>
10 public virtual FileUploadResponse UploadFileByUrl(string accessToken, string fileName, string fileUrl, string sourceId = "", string etag = "")
11 {
12     /* 若是須要上傳的文件不在本地,且該文件能夠經過指定的HTTP URL能夠下載,BIMFACE支持直接傳一個外部的HTTP文件URL, BIMFACE會去下載該文件,而無須用戶先下載,再上傳。 */
13 
14     //PUT 方式。例如:https://file.bimface.com/upload?name=example.rvt&url=http(s)://xxxxxxxxxxx
15     string url = string.Format(BimfaceConstants.FILE_HOST + "/upload?name={0}&url={1}", fileName.UrlEncode(Encoding.UTF8), fileUrl.UriEscapeDataString()); //文件的全名,使用URL編碼(UTF-8),最多256個字符
16     if (sourceId.IsNotNullAndWhiteSpace())
17     {
18         url = url + "&sourceId=" + sourceId;
19     }
20     if (etag.IsNotNullAndWhiteSpace())
21     {
22         url = url + "&etag=" + etag;
23     }
24 
25     BimFaceHttpHeaders headers = new BimFaceHttpHeaders();
26     headers.AddOAuth2Header(accessToken);
27 
28     try
29     {
30         FileUploadResponse response;
31 
32         HttpManager httpManager = new HttpManager(headers);
33         HttpResult httpResult = httpManager.Put(url);    
34         if (httpResult.Status == HttpResult.STATUS_SUCCESS)
35         {
36             response = httpResult.Text.DeserializeJsonToObject<FileUploadResponse>();
37         }
38         else
39         {
40             response = new FileUploadResponse
41             {
42                 Message = httpResult.RefText
43             };
44         }
45 
46         return response;
47     }
48     catch (Exception ex)
49     {
50         throw new Exception("指定外部文件url方式上傳文件發生異常!", ex);
51     }
52 }

 其中引用的 httpManager.Put() 方法以下:

 1 /// <summary>
 2 /// HTTP-PUT方法,(不包含body數據)。
 3 /// 發送 HTTP 請求並返回來自 Internet 資源的響應(HTML代碼)
 4 /// </summary>
 5 /// <param name="url">請求目標URL</param>
 6 /// <returns>HTTP-POST的響應結果</returns>
 7 public HttpResult Put(string url)
 8 {
 9     return RequestString(url, null, WebRequestMethods.Http.Put, null);
10 }
 1 /// <summary>
 2 ///  HTTP請求(包含文本的body數據)
 3 /// </summary>
 4 /// <param name="url">請求目標URL</param>
 5 /// <param name="data">主體數據(普通文本或者JSON文本)。若是參數中有中文,請使用合適的編碼方式進行編碼,例如:gb2312或者utf-8</param>
 6 /// <param name="method">請求的方法。請使用 WebRequestMethods.Http 的枚舉值</param>
 7 /// <param name="contentType"><see langword="Content-type" /> HTTP 標頭的值。請使用 ContentType 類的常量來獲取</param>
 8 /// <returns></returns>
 9 private HttpResult RequestString(string url, string data, string method, string contentType)
10 {
11     HttpResult httpResult = new HttpResult();
12     HttpWebRequest httpWebRequest = null;
13 
14     try
15     {
16         httpWebRequest = WebRequest.Create(url) as HttpWebRequest;
17         httpWebRequest.Method = method;
18         httpWebRequest.Headers = HeaderCollection;
19         httpWebRequest.CookieContainer = CookieContainer;
20         if (!string.IsNullOrWhiteSpace(contentType))
21         {
22             httpWebRequest.ContentType = contentType;// 此屬性的值存儲在WebHeaderCollection中。若是設置了WebHeaderCollection,則屬性值將丟失。因此放置在Headers 屬性以後設置
23         }
24         httpWebRequest.UserAgent = _userAgent;
25         httpWebRequest.AllowAutoRedirect = _allowAutoRedirect;
26         httpWebRequest.ServicePoint.Expect100Continue = false;
27 
28         if (data != null)
29         {
30             httpWebRequest.AllowWriteStreamBuffering = true;
31             using (Stream requestStream = httpWebRequest.GetRequestStream())
32             {
33                 requestStream.Write(EncodingType.GetBytes(data), 0, data.Length);//將請求參數寫入請求流中
34                 requestStream.Flush();
35             }
36         }
37 
38         HttpWebResponse httpWebResponse = httpWebRequest.GetResponse() as HttpWebResponse;
39         if (httpWebResponse != null)
40         {
41             GetResponse(ref httpResult, httpWebResponse);
42             httpWebResponse.Close();
43         }
44     }
45     catch (WebException webException)
46     {
47         GetWebExceptionResponse(ref httpResult, webException);
48     }
49     catch (Exception ex)
50     {
51         GetExceptionResponse(ref httpResult, ex, method, contentType);
52     }
53     finally
54     {
55         if (httpWebRequest != null)
56         {
57             httpWebRequest.Abort();
58         }
59     }
60 
61     return httpResult;
62 }
View Code
方式三:文件直傳
 
相關文章
相關標籤/搜索