Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

uploading a file and form Data in web Api and angularJS

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?

like image 316
LL Janneh Avatar asked May 24 '16 13:05

LL Janneh


2 Answers

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.

like image 158
Ihor Korotenko Avatar answered Nov 15 '22 19:11

Ihor Korotenko


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');
}
like image 31
Kyle Avatar answered Nov 15 '22 21:11

Kyle