I am following a guide in this blog on how to post form Data and a file. I am trying to upload the file in a directory on the server have done following but it is not working.
this is the Post function
[HttpPost]
public async Task<HttpResponseMessage> UploadFile(HttpRequestMessage request)
{
String root = HttpContext.Current.Server.MapPath("~/Logo/");
if (!request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
}
var data = await Request.Content.ParseMultipartAsync();
var httpRequest = HttpContext.Current.Request;
if (data.Files.ContainsKey("file"))
{
var file = data.Files["file"].File; // this is getting the file
var fileName = data.Files["file"].Filename; // this is getting the fileName
// System.Web.HttpPostedFile filePost = data.Files["file"];
String a = root + "" + Path.GetFileName(fileName);
string b = a;
var postedFile = fileName; // this is not working
var filePath = HttpContext.Current.Server.MapPath("~/Logo/" + fileName); // can someone help please
postedFile.SaveAs(filePath); // I
}
if (data.Fields.ContainsKey("description"))
{
var description = data.Fields["description"].Value;
}
return new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new StringContent("Thank you for uploading the file...")
};
}
how can I save the file to the Directory on the server?
currently I'm using the following code to upload image files, but it also work for any type of file:
public string UploadImage()
{
HttpRequestMessage request = this.Request;
if (!request.Content.IsMimeMultipartContent())
{
throw new HttpResponseException(new HttpResponseMessage((HttpStatusCode.UnsupportedMediaType)));
}
var context = HttpContext.Current.Request;
if (context.Files.Count > 0)
{
var resourcePhoto = new PhotoHelper(HttpContext.Current.Server.MapPath("~"));
var file = context.Files.AllKeys.FirstOrDefault();
var result = resourcePhoto.SaveResourceImage(context.Files[file], User.Identity.Name);
return result;
}
else
{
return null;
}
}
And in the SaveResourceImage
I do the following:
postedFile.SaveAs(resultPath);
That`s it.
Service
app.factory('myService', ['$http', function ($http) {
return {
uploadFile: function(url, file) {
return $http({
url: url,
method: 'POST',
data: file,
headers: { 'Content-Type': undefined }, //this is important
transformRequest: angular.identity //also important
});
},
otherFunctionHere: function(url, stuff) {
return $http.get(url);
}
};
}]);
Controller
app.controller('MainCtrl', ['$scope', 'myService', function($scope, myService) {
$scope.uploadFile = function() {
var fileInput = document.getElementById('fileInput');
fileInput.click();
//do nothing if there's no files
if(fileInput.files.length === 0) return;
var file = fileInput.files[0];
var payload = new FormData();
payload.append("stuff", "some string");
payload.append("file", file);
//use the service to upload the file
myService.uploadFile('/path/to/API', payload).then(function(response){
//success, file uploaded
}).catch(function(response){
//bummer
});
}
}]);
C# Controller
[HttpPost]
public JsonResult UploadFile(string stuff, HttpPostedFileBase file)
{
string fileName = Path.GetFileNameWithoutExtension(file.FileName);
string extension = Path.GetExtension(file.FileName);
//save the file
try
{
file.SaveAs('somePath' + fileName + extension);
}
catch (IOException exc)
{
return Json(new { status = 'error', message = exc.Message });
}
return Json('horray');
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With