葡萄藤的文件上传示例

时间:2016-10-26 05:42:18

标签: asp.net-web-api grapevine

我是Web API和REST服务的新手,希望构建一个接受文件上传的简单REST服务器。我发现葡萄藤很简单易懂。我找不到任何文件上传示例?

这是使用System.Web.Http

的示例
 var streamProvider = new MultipartFormDataStreamProvider(ServerUploadFolder);

 await Request.Content.ReadAsMultipartAsync(streamProvider);

但是葡萄藤Request属性没有任何方法可以做到这一点。有人能指点我一个例子吗?

1 个答案:

答案 0 :(得分:0)

如果您尝试将文件上传为二进制有效负载,请参阅GitHub上的this question/answer

如果您尝试从表单提交中上传文件,那将会有点棘手,因为尚未添加多部分有效负载解析器,但仍有可能。

以下代码示例未经测试完成,我只是把它写在了我的头顶,所以它可能不是最好的解决方案,但它是一个起点:

public static class RequestExtensions
{
    public static IDictionary<string, string> ParseFormUrlEncoded(this IHttpRequest request)
    {
        var data = new Dictionary<string, string>();

        foreach (var tuple in request.Payload.Split('='))
        {
            var parts = tuple.Split('&');
            var key = Uri.UnescapeDataString(parts[0]);
            var val = Uri.UnescapeDataString(parts[1]);
            if (!data.ContainsKey(key)) data.Add(key, val);
        }

        return data;
    }

    public static IDictionary<string, FormElement> ParseFormData(this IHttpRequest request)
    {
        var data = new Dictionary<string, FormElement>();
        var boundary = GetBoundary(request.Headers.Get("Content-Type"));

        if (boundary == null) return data;

        foreach (var part in request.Payload.Split(new[] { boundary }, StringSplitOptions.RemoveEmptyEntries))
        {
            var element = new FormElement(part);
            if (!data.ContainsKey(element.Name)) data.Add(element.Name, element);
        }

        return data;
    }

    private static string GetBoundary(string contenttype)
    {
        if (string.IsNullOrWhiteSpace(contenttype)) return null;

        return (from part in contenttype.Split(';', ',')
            select part.TrimStart().TrimEnd().Split('=')
            into parts
            where parts[0].Equals("boundary", StringComparison.CurrentCultureIgnoreCase)
            select parts[1]).FirstOrDefault();
    }
}

public class FormElement
{
    public string Name => _dispositionParams["name"];
    public string FileName => _dispositionParams["filename"];
    public Dictionary<string, string> Headers { get; private set; }
    public string Value { get; }

    private Dictionary<string, string> _dispositionParams;

    public FormElement(string data)
    {
        var parts = data.Split(new [] { "\r\n\r\n", "\n\n" }, StringSplitOptions.None);
        Value = parts[1];

        ParseHeaders(parts[0]);
        ParseParams(Headers["Content-Disposition"]);
    }

    private void ParseHeaders(string data)
    {
        Headers = data.TrimStart().TrimEnd().Split(new[] {"\r\n", "\n"}, StringSplitOptions.RemoveEmptyEntries).Select(header => header.Split(new[] {':'})).ToDictionary(parts => parts[0].TrimStart().TrimEnd(), parts => parts[1].TrimStart().TrimEnd());
    }

    private void ParseParams(string data)
    {
        _dispositionParams = new Dictionary<string, string>();

        foreach (var part in data.Split(new[] {';'}))
        {
            if (part.IndexOf("=") == -1) continue;
            var parts = part.Split(new[] {'='});
            _dispositionParams.Add(parts[0].TrimStart(' '), parts[1].TrimEnd('"').TrimStart('"'));
        }
    }
}

如果您正在寻找立即使用的异步内容,您可以尝试实现this stackoverflow question的答案,但尚未经过我的测试。