Reputation: 359
I have the following model :
public class FileModel
{
public byte[] FileData{get;set;}
public string FileName {get;set;}
}
I have coded a private Web API service which my Web application consumes.
When the user uploads files, I convert those files to a byte array, and send a List<FileModel>
to my Web API from C# code (not from an HTML page, since my Web API is private from my website), which saves my file and return results.
Web API method:
[HttpPost]
public UploadFiles(List<FileModel> files)
{
// Do work
}
The above code breaks if I upload many large-sized files - the code failed to serialize the large files' FileModel
s since they exceed the max serializing length.
How do I fix this issue? Is there any other way to upload files to Web API without exposing it to the users?
Upvotes: 3
Views: 12984
Reputation: 114
Here is some solution for that situation.
Your controller action will not accept any parameters as shown on code snippet.
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();
}
And the code above for front end sample.
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();
}
})
}
Upvotes: 2
Reputation: 5962
Add this in your web.config file.
<configuration>
<system.web>
<httpRuntime maxRequestLength ="1999999"/>
</system.web>
</configuration>
And also increase your content length in MVC config
file.
<system.webServer>
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="1999999999" />
</requestFiltering>
</security>
<system.webServer>
maxRequestLength
value is in kilobytes.
maxAllowedContentLength
value is in bytes.
You can change above size according to your requirements.
Upvotes: 1