我有以下型号:
public class FileModel
{
public byte[] FileData{get;set;}
public string FileName {get;set;}
}
我编写了一个我的Web应用程序使用的私有Web API服务。
当用户上传文件时,我将这些文件转换为字节数组,并从C#代码向我的Web API发送List<FileModel>
(而不是从HTML页面发送,因为我的Web API是我网站上的私有),这可以节省我的文件并返回结果。
Web API方法:
[HttpPost]
public UploadFiles(List<FileModel> files)
{
// Do work
}
如果我上传了许多大型文件,上面的代码会中断 - 代码无法序列化大文件FileModel
,因为它们超过了最大序列化长度。
如何解决此问题?是否有其他方法可以将文件上传到Web API而不将其暴露给用户?
答案 0 :(得分:1)
这是针对这种情况的一些解决方案。
您的控制器操作不会接受代码段中显示的任何参数。
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();
}
})
}
答案 1 :(得分:0)
在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
值以字节为单位。
您可以根据自己的要求更改尺寸。