Reputation: 966
I have some issues uploading file to my Web Api. I've created empty Web API Project and tried this code from some msdn page:
public class UploadController : ApiController
{
[HttpPost]
[Route("api/upload/file")]
public async Task<HttpResponseMessage> PostFormData()
{
// Check if the request contains multipart/form-data.
if (!Request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
string root = System.Web.HttpContext.Current.Server.MapPath("~/App_Data");
var provider = new MultipartFormDataStreamProvider(root);
try
{
// Read the form data.
await Request.Content.ReadAsMultipartAsync(provider);
// This illustrates how to get the file names.
foreach (MultipartFileData fileData in provider.FileData)
{
Trace.WriteLine(fileData.Headers.ContentDisposition.FileName);//get FileName
Trace.WriteLine("Server file path: " + fileData.LocalFileName);//get File Path
}
return Request.CreateResponse(HttpStatusCode.OK, "pass upload file successed!");
}
catch (System.Exception e)
{
return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, e);
}
}
}
To make sure I don't make any mistake on the frontend part I am using postman:
However initially I need to post this file from react app, and my code looks like this:
const UploadFile = connect(
mapStateToProps,
mapDispatchToProps,
)(
class extends React.Component {
constructor(props) {
super(props);
this.state = {
file: '',
};
}
async submit(e) {
e.preventDefault();
const formData = new FormData();
formData.append('file', this.state.file, { type: 'text/csv' });
// I am dispatching redux action here, but to simplify tests with file upload I am using axios post right here
// i tried different urls with and without action names
post('http://localhost:44370/api/upload/file', formData)
.catch(error => {
console.log(error);
})
.then(() => {});
}
setFile(e) {
this.setState({ file: e.target.files[0] });
}
render() {
return (
<div className="container-fluid">
<form onSubmit={e => this.submit(e)}>
<div className="col-sm-12 btn btn-primary">
File Upload
</div>
<h1>File Upload</h1>
<input type="file" onChange={e => this.setFile(e)} />
<button className="btn btn-primary" type="submit">
Upload
</button>
</form>
</div>
);
}
},
);
But I was never able to reach a breakpoint on my action, neither from react app nor from the postman. I am always getting 404 not found via postman and ERR_CONNECTION_ABORTED from react app.
I also tried this solution and a lot of other different approaches from the internet, also tried using HttpFileBase, but still no result.
Any ideas about how to change the code to be able to upload a file to Web Api Controller's action?
PS. I was able to upload file to asp.net core controller with such code:
[HttpPost]
public async Task<IActionResult> Post(IFormFile file)
{
if (file == null || file.Length == 0)
return Content("file not selected");
var fileId = Guid.NewGuid();
var path = Path.Combine(
Directory.GetCurrentDirectory(), "uploads",
file.FileName);
using (var stream = new FileStream(path, FileMode.Create))
await file.CopyToAsync(stream);
}
and the same react code but I need a solution for not .net core project, just a regular asp.net web api.
UPDATE According to a comment, I tried html page with nothing but form:
<form
name="form1"
method="post"
enctype="multipart/form-data"
action="http://localhost:44370/api/upload/file"
>
<div>
<label for="file">File</label>
<input name="file" type="file" />
</div>
<div>
<input type="submit" value="Submit" />
</div>
</form>
Upvotes: 1
Views: 9009
Reputation: 7187
Oh my.. Look at the error message in the screenshot.
it is not only 404, it is 404.13 - Content length too large.
. Are you trying to upload a very huge file?
You should modify request filtering settings if you are going to allow uploading of files with enormous sizes.
Look at the "things you can try" section in the screenshot:
Verify the configuration/system.webServer/security/requestFiltering/requestLimits@maxAllowedContentLength setting in the applicationhost.config or web.config file
Upvotes: 2