コード例 #1
0
        /// <summary>
        /// 大文件上传发送
        /// </summary>
        /// <param name="model">SaveBigFileModel</param>
        public UploadFileRes UploadBigFileSend(SaveBigFileSendModel model)
        {
            UploadFileRes uploadFileRes = new UploadFileRes();

            try
            {
                var handler = new WebRequestHandler();
                handler.ServerCertificateValidationCallback = delegate { return(true); };
                using (var httpClient = new HttpClient(handler))
                {
                    httpClient.DefaultRequestHeaders.Add("Authorization", model.TokenId);

                    Dictionary <string, List <object> > partInfo = new Dictionary <string, List <object> >();
                    if (!string.IsNullOrEmpty(model.PartsInfo))
                    {
                        partInfo = JsonConvert.DeserializeObject <Dictionary <string, List <object> > >(model.PartsInfo);
                    }
                    OSSAPIHelper ossHttpHelper = new OSSAPIHelper();

                    var json2    = "{\"docid\":\"" + model.Docid + "\",\"rev\":\"" + model.Rev + "\",\"uploadid\":\"" + model.UploadId + "\",\"partinfo\":" + JsonConvert.SerializeObject(partInfo) + "}";
                    var content2 = new StringContent(json2, Encoding.UTF8, "application/json");
                    var res2     = httpClient.PostAsync($"{Constant.OAuth2Url}/api/efast/v1/file/oscompleteupload", content2).Result;
                    var resStr2  = res2.Content.ReadAsStringAsync().Result;

                    int resCode2 = (int)res2.StatusCode;
                    // 若为错误返回码则抛出异常
                    if (resCode2 < 200 || resCode2 >= 300)
                    {
                        var errModel = JsonConvert.DeserializeObject <ErrorModel>(resStr2);
                        _log.Debug($"UploadBigFileSend Oscompleteupload Exception: {errModel.cause}, Code: {errModel.code}");
                        uploadFileRes.ErrorDetail = JsonConvert.SerializeObject(errModel.detail);
                        uploadFileRes.ErrorCode   = errModel.code;
                        return(uploadFileRes);
                    }

                    var resultsJson = resStr2.Split(new string[] { "\r\n\r\n" }, StringSplitOptions.None);
                    var bodyJson    = resultsJson[1].Split(new string[] { "--" }, StringSplitOptions.None).FirstOrDefault();
                    var headersJson = resultsJson[2].Split(new string[] { "--" }, StringSplitOptions.None).FirstOrDefault();

                    byte[]        body        = Encoding.UTF8.GetBytes(bodyJson);
                    JObject       returnJson  = (JObject)JsonConvert.DeserializeObject(headersJson);
                    JArray        authRequest = (JArray)returnJson["authrequest"];
                    string        method      = (string)authRequest[0];
                    string        url         = (string)authRequest[1];
                    List <string> resHeaders  = new List <string>();
                    for (int i = 2; i < authRequest.Count; i++)
                    {
                        resHeaders.Add((string)authRequest[i]);
                    }

                    var sendR = ossHttpHelper.SendReqToOSS(method, url, resHeaders, body);
                    sendR.Close();

                    string sendJson    = "{\"docid\":\"" + model.Docid + "\",\"rev\":\"" + model.Rev + "\"}";
                    var    sendContent = new StringContent(sendJson, Encoding.UTF8, "application/json");
                    var    sendRes     = httpClient.PostAsync($"{Constant.OAuth2Url}/api/efast/v1/file/osendupload", sendContent).Result;
                    var    sendResStr  = sendRes.Content.ReadAsStringAsync().Result;

                    int sendResCode = (int)sendRes.StatusCode;
                    // 若为错误返回码则抛出异常
                    if (sendResCode < 200 || sendResCode >= 300)
                    {
                        var errModel = JsonConvert.DeserializeObject <ErrorModel>(sendResStr);
                        _log.Debug($"UploadBigFileSend Osendupload Exception: {errModel.cause}, Code: {errModel.code}");
                        uploadFileRes.ErrorDetail = JsonConvert.SerializeObject(errModel.detail);
                        uploadFileRes.ErrorCode   = errModel.code;
                        return(uploadFileRes);
                    }
                    uploadFileRes.FileName = model.FileName;
                    uploadFileRes.FileId   = model.Docid;
                }
                return(uploadFileRes);
            }
            catch (Exception ex)
            {
                _log.Debug($"UploadBigFileSend Exception: {ex.Message}");
                throw ex;
            }
        }
コード例 #2
0
        /// <summary>
        /// 文件上传
        /// </summary>
        /// <param name="model">SaveFileModel</param>
        public UploadFileRes UploadFile(SaveFileModel model)
        {
            UploadFileRes uploadFileRes = new UploadFileRes();

            try
            {
                var handler = new WebRequestHandler();
                handler.ServerCertificateValidationCallback = delegate { return(true); };
                using (var httpClient = new HttpClient(handler))
                {
                    httpClient.DefaultRequestHeaders.Add("Authorization", model.TokenId);

                    // 文件body
                    byte[] body = model.Base64Str;
                    var    json = "{\"docid\":\"" + model.Docid + "\",\"name\":\"" + model.FileName.Trim() + "\",\"length\":" + body.Length + ",\"ondup\":" + model.Ondup + "}";

                    var content = new StringContent(json, Encoding.UTF8, "application/json");
                    var res     = httpClient.PostAsync($"{Constant.OAuth2Url}/api/efast/v1/file/osbeginupload", content).Result;
                    var resStr  = res.Content.ReadAsStringAsync().Result;

                    int resCode = (int)res.StatusCode;
                    // 若为错误返回码则抛出异常
                    if (resCode < 200 || resCode >= 300)
                    {
                        var errModel = JsonConvert.DeserializeObject <ErrorModel>(resStr);
                        _log.Debug($"UploadFile Osbeginupload Exception: {errModel.cause}, Code: {errModel.code}");
                        uploadFileRes.ErrorDetail = JsonConvert.SerializeObject(errModel.detail);
                        uploadFileRes.ErrorCode   = errModel.code;
                        return(uploadFileRes);
                    }

                    var    dynamicObj = JsonConvert.DeserializeObject <dynamic>(resStr);
                    string method     = dynamicObj["authrequest"][0].Value;
                    string url        = dynamicObj["authrequest"][1].Value;
                    string rev        = dynamicObj["rev"].Value;
                    string docid      = dynamicObj["docid"].Value;
                    uploadFileRes.FileId   = docid;
                    uploadFileRes.FileName = model.FileName.Trim();

                    List <string> headers = new List <string>();
                    for (int i = 2; i < dynamicObj["authrequest"].Count; ++i)
                    {
                        headers.Add(dynamicObj["authrequest"][i].Value);
                    }

                    OSSAPIHelper    ossHttpHelper = new OSSAPIHelper();
                    HttpWebResponse ossResult     = ossHttpHelper.SendReqToOSS(method, url, headers, body);
                    int             oosCode       = (int)ossResult.StatusCode;

                    // 若为错误返回码则抛出异常
                    if (oosCode < 200 || oosCode >= 300)
                    {
                        Stream resStream = ossResult.GetResponseStream();
                        string errBody   = string.Empty;
                        using (StreamReader reader = new StreamReader(resStream, Encoding.UTF8))
                        {
                            errBody = reader.ReadToEnd();
                        }
                        var errModel = JsonConvert.DeserializeObject <ErrorModel>(errBody);
                        _log.Debug($"UploadFile SendReqToOSS Exception: {errModel.cause}");
                        uploadFileRes.ErrorDetail = JsonConvert.SerializeObject(errModel.detail);
                        uploadFileRes.ErrorCode   = errModel.code;
                        ossResult.Close();
                        return(uploadFileRes);
                    }
                    ossResult.Close();

                    string sendJson    = "{\"docid\":\"" + docid + "\",\"rev\":\"" + rev + "\"}";
                    var    sendContent = new StringContent(sendJson, Encoding.UTF8, "application/json");
                    var    sendRes     = httpClient.PostAsync($"{Constant.OAuth2Url}/api/efast/v1/file/osendupload", sendContent).Result;
                    var    sendResStr  = sendRes.Content.ReadAsStringAsync().Result;

                    int sendCode = (int)sendRes.StatusCode;
                    // 若为错误返回码则抛出异常
                    if (sendCode < 200 || sendCode >= 300)
                    {
                        var errModel = JsonConvert.DeserializeObject <ErrorModel>(sendResStr);
                        _log.Debug($"UploadFile Oosendupload Exception: {errModel.cause}");
                        uploadFileRes.ErrorDetail = JsonConvert.SerializeObject(errModel.detail);
                        uploadFileRes.ErrorCode   = errModel.code;
                        return(uploadFileRes);
                    }
                }
                return(uploadFileRes);
            }
            catch (Exception ex)
            {
                _log.Debug($"UploadFile Exception: {ex.Message}");
                throw ex;
            }
        }
コード例 #3
0
        /// <summary>
        /// 大文件上传
        /// </summary>
        /// <param name="model">SaveBigFileModel</param>
        public UploadFileRes UploadBigFile(SaveBigFileModel model)
        {
            UploadFileRes uploadFileRes = new UploadFileRes();

            try
            {
                var handler = new WebRequestHandler();
                handler.ServerCertificateValidationCallback = delegate { return(true); };
                using (var httpClient = new HttpClient(handler))
                {
                    httpClient.DefaultRequestHeaders.Add("Authorization", model.TokenId);

                    byte[] buf       = model.FileBytes;
                    int    writeSize = buf.Length; // 记录当前块写入的字节
                    Dictionary <string, List <object> > partInfo = new Dictionary <string, List <object> >();
                    if (!string.IsNullOrEmpty(model.PartsInfo))
                    {
                        partInfo = JsonConvert.DeserializeObject <Dictionary <string, List <object> > >(model.PartsInfo);
                    }

                    // 文件body
                    var json1 = "{\"docid\":\"" + model.Docid + "\",\"rev\":\"" + model.Rev + "\",\"uploadid\":\"" + model.UploadId + "\",\"parts\":\"" + model.PartIndex + "\"}";

                    var content1 = new StringContent(json1, Encoding.UTF8, "application/json");
                    var res1     = httpClient.PostAsync($"{Constant.OAuth2Url}/api/efast/v1/file/osuploadpart", content1).Result;
                    var resStr1  = res1.Content.ReadAsStringAsync().Result;
                    int resCode1 = (int)res1.StatusCode;
                    // 若为错误返回码则抛出异常
                    if (resCode1 < 200 || resCode1 >= 300)
                    {
                        var errModel = JsonConvert.DeserializeObject <ErrorModel>(resStr1);
                        _log.Debug($"UploadBigFile Osuploadpart Exception: {errModel.cause}, Code: {errModel.code}");
                        uploadFileRes.ErrorDetail = JsonConvert.SerializeObject(errModel.detail);
                        uploadFileRes.ErrorCode   = errModel.code;
                        return(uploadFileRes);
                    }

                    var jResult = JsonConvert.DeserializeObject <AuthRequestsModel>(resStr1);
                    var results = JsonConvert.DeserializeObject <Dictionary <string, List <string> > >(jResult.authrequests.ToString());

                    List <string> headers         = new List <string>();
                    List <string> authRequestList = new List <string>();
                    results.TryGetValue(model.PartIndex.ToString(), out authRequestList);
                    for (int i = 2; i < authRequestList.Count; ++i)
                    {
                        string header = authRequestList[i];
                        headers.Add(header);
                    }

                    string       etag          = null;
                    OSSAPIHelper ossHttpHelper = new OSSAPIHelper();

                    // 文件块上传
                    using (HttpWebResponse ossResult = ossHttpHelper.SendReqToOSS(authRequestList[0], authRequestList[1], headers, buf))
                    {
                        // 获取etag,由于报头中"etag"可能为"Etag","ETag","ETAG"等情况,故这里对报头key值进行遍历,将key值变为大写后与"ETAG"进行比较,若相等则让etag等于其value,退出循环。
                        WebHeaderCollection headerArray = ossResult.Headers;
                        for (int i = 0; i < headerArray.Count; ++i)
                        {
                            string key = headerArray.GetKey(i);
                            if (key.ToUpper().Equals("ETAG"))
                            {
                                etag = headerArray[key];
                                i    = headerArray.Count;
                            }
                        }
                    }

                    List <object> tempList = new List <object>();
                    tempList.Add(etag);
                    tempList.Add(writeSize);
                    partInfo.Add(model.PartIndex.ToString(), tempList);

                    uploadFileRes.FileName = JsonConvert.SerializeObject(partInfo);
                    return(uploadFileRes);
                }
            }
            catch (Exception ex)
            {
                _log.Debug($"UploadBigFile Exception: {ex.Message}");
                throw ex;
            }
        }
コード例 #4
0
        /// <summary>
        /// GetDownloadFileStream
        /// </summary>
        /// <param name="model">OpenFileModel</param>
        /// <param name="fileName">fileName</param>
        /// <returns>FileStream</returns>
        private DownloadRes GetDownloadFileStream(OpenFileModel model)
        {
            DownloadRes downloadRes = new DownloadRes();
            string      resStr      = string.Empty;
            var         handler     = new WebRequestHandler();

            handler.ServerCertificateValidationCallback = delegate { return(true); };
            using (var httpClient = new HttpClient(handler))
            {
                httpClient.DefaultRequestHeaders.Add("Authorization", model.TokenId);

                var json = "{\"docid\":\"" + model.FileId + "\"}";
                if (!string.IsNullOrEmpty(model.Rev))
                {
                    json = "{\"docid\":\"" + model.FileId + "\",\"rev\":\"" + model.Rev + "\"}";
                }
                var content = new StringContent(json, Encoding.UTF8, "application/json");
                var res     = httpClient.PostAsync($"{Constant.OAuth2Url}/api/efast/v1/file/osdownload", content).Result;
                resStr = res.Content.ReadAsStringAsync().Result;


                int resCode = (int)res.StatusCode;
                // 若为错误返回码则抛出异常
                if (resCode < 200 || resCode >= 300)
                {
                    var errModel = JsonConvert.DeserializeObject <ErrorModel>(resStr);
                    _log.Debug($"GetDownloadFileStream Exception: {errModel.cause}, Code: {errModel.code}");
                    downloadRes.ErrorCode   = errModel.code;
                    downloadRes.ErrorDetail = JsonConvert.SerializeObject(errModel.detail);
                    return(downloadRes);
                }
            }

            var    dynamicObj = JsonConvert.DeserializeObject <dynamic>(resStr);
            string method     = dynamicObj["authrequest"][0].Value;
            string url        = dynamicObj["authrequest"][1].Value;

            downloadRes.FileName = dynamicObj["name"].Value;

            List <string> headers = new List <string>();

            for (int i = 2; i < dynamicObj["authrequest"].Count; ++i)
            {
                headers.Add(dynamicObj["authrequest"][i].Value);
            }

            OSSAPIHelper    ossHttpHelper = new OSSAPIHelper();
            HttpWebResponse ossResult     = ossHttpHelper.SendReqToOSS(method, url, headers, null);

            downloadRes.Stream = ossResult.GetResponseStream();

            int oosCode = (int)ossResult.StatusCode;

            // 若为错误返回码则抛出异常
            if (oosCode < 200 || oosCode >= 300)
            {
                string errBody = string.Empty;
                using (StreamReader reader = new StreamReader(downloadRes.Stream, Encoding.UTF8))
                {
                    errBody = reader.ReadToEnd();
                }
                var errModel = JsonConvert.DeserializeObject <ErrorModel>(errBody);
                _log.Debug($"UploadFile SendReqToOSS Exception: {errModel.cause}");
                downloadRes.ErrorCode   = errModel.code;
                downloadRes.ErrorDetail = JsonConvert.SerializeObject(errModel.detail);
            }
            return(downloadRes);
        }