上传文件到网络API
我有以下型号:上传文件到网络API
public class FileModel
{
public byte[] FileData{get;set;}
public string FileName {get;set;}
}
我已经编写这我的Web应用程序消耗私有的Web API服务。 当用户上传文件时,我将这些文件转换为字节数组,并从C#代码(不是从HTML页面发送List<FileModel>
到我的Web API,因为我的Web API从我的网站是私人的),这将保存我的文件和返回结果。
的Web API方法:
[HttpPost]
public UploadFiles(List<FileModel> files)
{
// Do work
}
上面的代码休息,如果我上传许多大型文件 - 代码的失败,因为它们超出了最大长度序列化序列化大文件FileModel
秒。
如何解决此问题?有没有其他方法可以将文件上传到Web API而不会将其暴露给用户?
将此项添加到您的web.config文件中。
<configuration>
<system.web>
<httpRuntime maxRequestLength ="1999999"/>
</system.web>
</configuration>
,并增加在MVC config
文件内容的长度。
<system.webServer>
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="1999999999" />
</requestFiltering>
</security>
<system.webServer>
maxRequestLength
值以千字节为单位。
maxAllowedContentLength
值以字节为单位。
您可以根据您的要求改变上述尺寸。
感谢但maxRequestLength不是我的问题的原因。 –
当我使用httpClient.PostAsJsonAsync >(“API URL”,postObj)。我返回未找到Web API方法的响应。 –
但这仅仅适用于大文件 –
这是针对这种情况的一些解决方案。
您的控制器操作不会接受任何参数,如代码段所示。
public async Task<HttpResponseMessage> PostByteArrayAsync()
{
string root = HttpContext.Current.Server.MapPath("~/folder");
var provider = new MultipartFormDataStreamProvider(root);
await Request.Content.ReadAsMultipartAsync(provider);
foreach (var file in provider.FileData)
{
var buffer = File.ReadAllBytes(file.LocalFileName);
// store to db and other stuff
}
return Ok();
}
以上代码为前端样本。
UploadData(event) {
this.setState({ loading: true });
event.preventDefault();
let data = new FormData();
let fileData = document.querySelector('input[type="file"]').files[0];
data.append("data", fileData);
let that = this;
fetch("api/upload", {
method: "POST",
"Content-Type": "multipart/form-data",
"Accept": "application/json",
body: data
}).then(function (res) {
if (res.ok) {
call('api', 'GET').then(response => { response.error ? response.message : that.props.change(response); that.setState({ loading: false }) });
}
else {
that.setState({ loading: false });
that.failedMsg();
}
})
}
嗨感谢您的响应,但我没有尝试将文件发送到我的Web API直接。我发布文件到我的MVC操作控制器,并使我的控制器操作POST文件到我的Web API。我不希望我的Web API网址因为它的私有(即,特定于我的网站) –
的可能的复制[如何上传与进度ASP.NET MVC4网络API一个大文件(https://stackoverflow.com/questions/15506648/how-to-upload-a-large-file -with-asp-net-mvc4-web-api-with-progressbar) – Liam
使用块字节方法异步上传。 https://stackoverflow.com/questions/583970/need-loop-to-copy-chunks-from-byte-array –
@NikhilKS我不想做多个网络API调用。 –