I used this following code to upload file to server, but the file is not uploaded.
Html:
Instead of submit button can you try with normal button -
<form enctype="multipart/form-data">
<label>
Using JQuery
</label>
<input name="file" type="file" id="me" />
<input type="button" id="Upload" value="Upload" />
</form>
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$(function () {
$('#Upload').click(function () {
var formData = new FormData();
var opmlFile = $('#me')[0];
formData.append("opmlFile", opmlFile.files[0]);
$.ajax({
url: 'http://localhost:23133/api/file',
type: 'POST',
data: formData,
cache: false,
contentType: false,
processData: false
});
});
});
</script>
Controller Action -
public HttpResponseMessage Post()
{
HttpResponseMessage result = null;
var httpRequest = HttpContext.Current.Request;
// Check if files are available
if (httpRequest.Files.Count > 0)
{
var files = new List<string>();
// interate the files and save on the server
foreach (string file in httpRequest.Files)
{
var postedFile = httpRequest.Files[file];
var filePath = HttpContext.Current.Server.MapPath("~/" + postedFile.FileName);
postedFile.SaveAs(filePath);
files.Add(filePath);
}
// return result
result = Request.CreateResponse(HttpStatusCode.Created, files);
}
else
{
// return BadRequest (no file(s) available)
result = Request.CreateResponse(HttpStatusCode.BadRequest);
}
return result;
}
Output -
Your javascript isn't referencing the correct file input control.
You need to change this var opmlFile = $('#opmlFile')[0];
To this var opmlFile = $('#myFile')[0];