如何使用http发送文件

问题描述 投票:0回答:2

我正在尝试从.net客户端使用.net通过StreamContent服务器(文件位于服务器计算机上)下载文件。但是,当启动请求时,我得到异常:

例外

Stream does not support reading.

客户

class Program {
        static async Task Main(string[] args) {
            HttpClient client = new HttpClient();
            using (FileStream stream = new FileStream("txt.path", FileMode.OpenOrCreate, FileAccess.Write)) {
                var content = new StreamContent(stream);
                var response = await client.PostAsync("http://localhost:5300/get", content);
            }
        }
    }

服务器

  public void Configure(IApplicationBuilder app, IHostingEnvironment env) {
            if (env.IsDevelopment()) {
                app.UseDeveloperExceptionPage();
            }
            string fname = "dld.txt";

            app.Run(async (context) => {
                if (!(context.Request.Path == "get")) {
                    return;
                }
                File.WriteAllText(fname, "data is:" + DateTime.Now.ToString());

                FileStream fs = new FileStream(fname, FileMode.Open, FileAccess.Read);
                using (Stream stream = context.Response.Body) {
                    await fs.CopyToAsync(stream);
                }

            });
        }
file .net-core stream
2个回答
1
投票

嗨你可以像这样使用:

HttpContent stringContent = new StringContent(paramString); //if you want to use string
HttpContent fileStreamContent = new StreamContent(paramFileStream); //if you want to use  file stream
HttpContent bytesContent = new ByteArrayContent(paramFileBytes);// if you want to use aray of bytes
using (var client = new HttpClient())
{
    using (var formData = new MultipartFormDataContent())
    {
        formData.Add(stringContent, "param", "param");
        formData.Add(fileStreamContent, "file", "file");
        formData.Add(bytesContent, "file", "file");
        var response = await client.PostAsync("some URL", formData);
        if (!response.IsSuccessStatusCode)
        {
            return null;
        }
        return await response.Content.ReadAsStreamAsync();
    }
}

0
投票

我无法获取文件,因为我想使用Request.Body流作为接收器。我希望server在此流上写入数据(我认为Request流可以两种方式使用)。

我通过使用Response流解决了它:

客户

static async Task Main(string[] args) {
            HttpClient client = new HttpClient();
            using (FileStream stream = new FileStream("data.txt", FileMode.OpenOrCreate, FileAccess.Write)) {
                var content = new StringContent("not important");
                var response = await client.PostAsync("http://localhost:5300/get",content);
                await response.Content.CopyToAsync(stream);
            }
        }
© www.soinside.com 2019 - 2024. All rights reserved.