我想知道如何最好地处理文件上传和添加到要使用 ASP.NET Web API 2 上传的文件的附加信息,而无需 MVC 组件。我在网上谷歌了一下,我可以告诉你我比我预期的更困惑。
附加信息将存储在 db 和磁盘上的文件中。
到目前为止,我正在构建的 Web API 应用程序不支持 multipart/form-data。它仅支持默认媒体类型。我知道我需要创建一个媒体格式化程序。
请帮忙。
最佳答案
我写了 Javascript split File 并上传到 WEB API 。我想你可以引用我的后端代码
在前端,您需要使用以下代码上传文件
var xhr = new self.XMLHttpRequest();
xhr.open('POST', url, false);
xhr.setRequestHeader('Content-Type', 'application/octet-stream');
xhr.send(chunk);
在后端使用 Request.InputStream.Read 来捕获您的文件字节
[HttpPost]
[ValidateInput(false)]
public string fileUpload(string filename)
{
byte[] file = new byte[Request.InputStream.Length];
Request.InputStream.Read(file, 0, Convert.ToInt32(Request.InputStream.Length));
BinaryWriter binWriter = new BinaryWriter(new MemoryStream());
binWriter.Write(file);
StreamReader reader = new StreamReader(binWriter.BaseStream);
reader.BaseStream.Position = 0;
//This example is recevied text file
while ((line = reader.ReadLine()) != null)
{
};
}
关于ASP.NET Web API 2 文件上传,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22835246/