1. 程式人生 > >c# 後臺post,包含file檔案

c# 後臺post,包含file檔案

http request 相關

        private bool Upload(KeyValuePair<string, string>[] paramString,Stream paramFileStream)
        {
            var actionUrl = $"{_websiteUrl}/********";

            byte[] paramFileBytes = new byte[paramFileStream.Length];
            paramFileStream.Read(paramFileBytes, 0, paramFileBytes.Length);
            // 設定當前流的位置為流的開始 
            paramFileStream.Seek(0, SeekOrigin.Begin);
            Func<Task<bool>> task = async () =>
            {
                using (var client = CreateHttpClient())
                {
                    using (var formData = new MultipartFormDataContent())
                    {

                        foreach (var keyValuePair in paramString)
                        {
                            formData.Add(new StringContent(keyValuePair.Value), keyValuePair.Key);
                        }
                        //var fileContent = new ByteArrayContent(paramFileBytes);
                        HttpContent fileStreamContent = new StreamContent(paramFileStream);
                        fileStreamContent.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("form-data")
                        {
                            Name = "files",
                            Size = 1,
                            FileName = "201809.xlsx"
                        };
                        fileStreamContent.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
                        //formData.Add(fileContent, "files");
                        formData.Add( fileStreamContent, "files", "201809.xlsx");
                        client.DefaultRequestHeaders.Add("UserToken", _clientAuth.GetToken());
                        var respMessage = await client.PostAsync(FixUrl(actionUrl), formData).ConfigureAwait(false);
                        if (!respMessage.IsSuccessStatusCode)
                        {
                            return false;
                        }
                        //respMessage.EnsureSuccessStatusCode();
                        Byte[] rawBytes = await respMessage.Content.ReadAsByteArrayAsync().ConfigureAwait(false);
                        var content = ClientEncoding.GetString(rawBytes, 0, rawBytes.Length);
                        return true;
                    }
                }
            };
            return RunSync(task);
        }    

 

相關方法

        public static TResult RunSync<TResult>(Func<Task<TResult>> func, bool await = false)
        {
            CultureInfo cultureUi = CultureInfo.CurrentUICulture;
            CultureInfo culture = CultureInfo.CurrentCulture;
            return _myTaskFactory.StartNew<Task<TResult>>(delegate
            {
                Thread.CurrentThread.CurrentCulture = culture;
                Thread.CurrentThread.CurrentUICulture = cultureUi;
                return func();
            }).Unwrap<TResult>().ConfigureAwait(await).GetAwaiter().GetResult();
        }