如何在 C# Web API 中流式传输文件上传以进行数据库存储
本文关键字:文件 存储 数据库 传输 Web API | 更新日期: 2023-09-27 18:33:26
我花了几个小时研究许多发现的示例,但没有成功,因为在Web表单应用程序中执行的操作非常简单。 也就是说,上传一个或多个文件并将它们存储在 sql 服务器中。
在 Web 表单 (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新手,我显然已经超出了我的头脑。
任何人都可以指导我如何将文件内容放入我可以获取要发送到数据库的字节的流中?
这是我遇到此问题时的解决方案:
客户:
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);
}