4

对于在 Web 表单应用程序中超级简单的操作,我花了数小时处理许多找到的示例,但都没有成功。即上传一个或多个文件并存储在sql server中。

在网络表单(vb.net)中,我可以这样做:

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

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

现在 C# Web-Api:

我现在通过 Web-Api 将上传保存到文件系统的看似不错的示例是:

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 的新手,我显然已经不知所措了。

谁能指导我如何将文件内容放入流中,我可以将字节发送到数据库?

4

1 回答 1

1

这是我遇到此问题时的解决方案:

客户:

 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);
}
于 2014-08-01T09:52:53.463 回答