如何流在C#中的Web API文档上传数据库存储 [英] How to stream file upload in C# Web Api for database storage

查看:180
本文介绍了如何流在C#中的Web API文档上传数据库存储的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经花了几个小时的工作中发现许多例子都没有成功,什么是超级简单的Web窗体应用程序执行。也就是说,上载一个或多个文件,并将它们存储在SQL Server

I've spent hours working many found examples without success for what is super simple to do in a web forms application. That is, upload one or more files and store them in sql server.

在Web窗体(vb.net)我可以做到这一点:

In web forms (vb.net) I can do this:

Dim fs As Stream = fileUpload1.PostedFile.InputStream
        Dim br As New BinaryReader(fs)
        Dim bytes As Byte() = br.ReadBytes(fs.Length)

        'insert the file into database
        Dim strQuery As String = "INSERT INTO files ([name], [type], [file]) VALUES (@Name, @ContentType, @Data)"
        Dim cmd As New SqlCommand(strQuery)

        cmd.Parameters.Add("@Name", SqlDbType.VarChar).Value = filename
        cmd.Parameters.Add("@ContentType", SqlDbType.VarChar).Value() = contenttype
        cmd.Parameters.Add("@Data", SqlDbType.Binary).Value = bytes

然后执行数据库执行语句......完成!

Then do the database execute statements......done!

现在C#Web的API:

Now C# Web-Api:

看似很好的例子,我现在可以节省上传通过Web的API文件格式为:

The seemingly good example I have now that saves uploads to the filesystem via Web-Api is:

public Task<IEnumerable<FileDesc>> Old()
    {
        string folderName = "uploads";
        string PATH = HttpContext.Current.Server.MapPath("~/" + folderName);
        string rootUrl = Request.RequestUri.AbsoluteUri.Replace(Request.RequestUri.AbsolutePath, String.Empty);

        if (Request.Content.IsMimeMultipartContent())
        {
            var streamProvider = new MultipartFormDataStreamProvider(PATH);
            var task = Request.Content.ReadAsMultipartAsync(streamProvider).ContinueWith<IEnumerable<FileDesc>>(t =>
            {
                if (t.IsFaulted || t.IsCanceled)
                {
                    throw new HttpResponseException(HttpStatusCode.InternalServerError); 
                }
                var fileInfo = streamProvider.FileData.Select(i =>
                {
                    var info = new FileInfo(i.LocalFileName);
                    return new FileDesc(info.Name, rootUrl + "/" + folderName + "/" + info.Name, info.Length / 1024);
                });
                return fileInfo;
            });
            return task;
        }
        else
        {
            throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotAcceptable, "This request is not properly formatted"));
        }
    }

我似乎无法弄清楚如何让每一个分段文件内容流,这样我就可以发送到数据库。我见过的帖子谈论MultipartMemoryStreamProvider和MultipartStreamProvider,但我还没有想出如何使用它们。我很清楚我的头为C#和Web的API新手。

I cannot seem to figure out how to get each multipart file content stream so that I can send to the database. I've seen posts talking about MultipartMemoryStreamProvider and MultipartStreamProvider but I haven't figured out how to use them. I'm clearly over my head as a C# and Web-Api newbie.

谁能告诉我如何获得文件内容到流,我可以得到字节发送到数据库?

Can anyone direct me on how to get the file contents into a stream I can get the bytes to send to the db?

推荐答案

下面是我的解决方案时,我遇到过这个问题:

Here's my solution when I encountered this issue:

客户:

 public async Task UploadImage(byte[] image, string url)
        {
            Stream stream = new System.IO.MemoryStream(image);
            HttpStreamContent streamContent = new HttpStreamContent(stream.AsInputStream());

            Uri resourceAddress = null;
            Uri.TryCreate(url.Trim(), UriKind.Absolute, out resourceAddress);
            Windows.Web.Http.HttpRequestMessage request = new Windows.Web.Http.HttpRequestMessage(Windows.Web.Http.HttpMethod.Post, resourceAddress);
            request.Content = streamContent;

            var httpClient = new Windows.Web.Http.HttpClient();
            var cts = new CancellationTokenSource();
            Windows.Web.Http.HttpResponseMessage response = await httpClient.SendRequestAsync(request).AsTask(cts.Token);
        }

控制器:

public async Task<HttpResponseMessage> Post()
{
    Stream requestStream = await this.Request.Content.ReadAsStreamAsync();
    byte[] byteArray = null;
    using (MemoryStream ms = new MemoryStream())
    {
        await requestStream.CopyToAsync(ms);
        byteArray = ms.ToArray();
    }
    .
    .
    .
    return Request.CreateResponse(HttpStatusCode.OK);
}

这篇关于如何流在C#中的Web API文档上传数据库存储的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆