任何人都知道如何从ASP.net上传文件到远程休息服务(不是WCF)

时间:2015-04-29 01:48:49

标签: c# asp.net rest

我需要在ASP.net c#中实现上传方法,将文件上传到远程休息服务,而不是上传到我的本地机器。

我写了一个函数,将数据发布到其余服务,现在我想知道如何将文件流发布到其余服务?

我使用以下代码行发布数据

if (!string.IsNullOrEmpty(PostData) && Method == HttpVerb.POST)
{
    var encoding = new UTF8Encoding();
    var bytes = Encoding.GetEncoding("iso-8859-1").GetBytes(PostData);
    request.ContentLength = bytes.Length;

    using (var writeStream = request.GetRequestStream())
    {
        writeStream.Write(bytes, 0, bytes.Length);
    }
}

知道如何让postData成为我的文件流吗?而不是字符串。

1 个答案:

答案 0 :(得分:2)

过去我使用过这种技术:

private static StreamContent CreateFileContent(Stream fileStream, string fileName, string contentType)
{
    var fileContent = new StreamContent(fileStream);

    fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("form-data")
    {
        Name = "\"files\"",
        FileName = "\"" + fileName + "\""
    }; // the extra quotes are key here

    fileContent.Headers.ContentType = new MediaTypeHeaderValue(contentType);

    return fileContent;
}

然后通过这样的HttpClient上传:

private async Task UploadFile(HttpClient client, Stream fileStream, string filename)
{
    //HttpClient initialized by caller
    using (var content = new MultipartFormDataContent())
    {
        //file contains XML
        content.Add(CreateFileContent(fileStream, filename, "text/xml"));
        var resp = await client.PostAsync("the/rest/endpoint", content);
        resp.EnsureSuccessStatusCode();
    }

    return;
    // Error handling left as an exercise for the reader.
}