8

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?

5 Answers 5

7

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.

Sign up to request clarification or add additional context in comments.

Comments

5

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');
}

2 Comments

You saved my day! Ajax post will set correct content-type header for FormData only if you explicitly set Content-Type to undefined!
this only accepts one file, right? how could you modify this to accept multiple files?
0

I was able to adjust the code with this snippet and that does the trick

 var httpPostedFile = HttpContext.Current.Request.Files["file"];                                                 // this is not working
                var filePath = HttpContext.Current.Server.MapPath("~/Logo/" + fileName);    // can someone help please 
                httpPostedFile.SaveAs(filePath);

Comments

0

I have tried this way on Angular 1.5. So I have controller and repository in front end.I didnt save it in local drive. But there is a buffer, which we can save wherever we want.

Controller:

function submit() {

        modelTemplateRepository.add(model.modelTemplate, model.file)
            .then(function(response) {
                if (response && response.status) {
                    if (response.status === 422) {
                        model.apiError = response.data;
                        model.isSubmitting = false;
                    }
                    else {
                        onSaved(response.data);
                    }
                }
            });
    }

Repository:

function add(modelTemplate, file) {

        var fd = new FormData();

        fd.append('file', file);
        fd.append('modelTemplate',angular.toJson(modelTemplate));

        return $http.post(config.ApiEndpoint + '/modeltemplate', fd,
        {
            transformRequest: angular.identity,
            headers: {'Content-Type': undefined}
        })
            .then(addComplete)
            .catch(function(data) {
                return angular.fromJson(data);
            });

        function addComplete(response, status, headers, config) {
            return response;
        }
    }

API:

[HttpPost]
    [Route("api/modeltemplate")]
    public async Task<IHttpActionResult> Post()
    {

        if (!Request.Content.IsMimeMultipartContent())
            throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);

        var provider = new MultipartMemoryStreamProvider();

        await Request.Content.ReadAsMultipartAsync(provider);

        var file = provider.Contents.First(x => x.Headers.ContentDisposition.Name == "\"file\"");

        var filename = "";
        var buffer = new byte[0];

        if (file.Headers.ContentDisposition.FileName != null)
        {
            filename = file.Headers.ContentDisposition.FileName.Trim('\"');
            buffer = await file.ReadAsByteArrayAsync();
        }

        var formContent = provider.Contents.First(x => x.Headers.ContentDisposition.Name == "\"modelTemplate\"");
        Task<string> stringContentsTask = formContent.ReadAsStringAsync();
        var stringContents = stringContentsTask.Result;
        var dto = Newtonsoft.Json.JsonConvert.DeserializeObject<dynamic>(stringContents);

        var result = ApiHelper.Add<dynamic>("modeltemplate", dto);

        return Ok(result);
    }

Comments

-1

For saving file to Server, you can make use of MultipartFormDataStreamProvider. Also I don't think you need to pass in request as one of the parameter.

string root = HttpContext.Current.Server.MapPath("~/App_Data");
var provider = new MultipartFormDataStreamProvider(root);

And then can get handle to file as

// Read the form data.
        await Request.Content.ReadAsMultipartAsync(provider);

        // This illustrates how to get the file names.
        foreach (MultipartFileData file in provider.FileData)
        {
            Trace.WriteLine(file.Headers.ContentDisposition.FileName);
            Trace.WriteLine("Server file path: " + file.LocalFileName);
        }
        return Request.CreateResponse(HttpStatusCode.OK);

This page on ASP.NET give a good overview of how to do it..

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.