简体   繁体   中英

How to pass parameters from angular $upload to web api

I'm having trouble passing parameters from my UI to my upload logic

I'm setting up the upload request like this

$upload.upload({
        url: "./api/import/ImportRecords",
        method: "POST",
        data: { fileUploadObj: $scope.fileUploadObj },
        fields: { 'clientId': $scope.NewImport.clientId },
        file: $scope.$file
    }).progress(function (evt) {
    }).success(function (data, status, headers, config) {
    }).error(function (data, status, headers, config) {
});

My API is setup as follows:

[HttpPost]
public IHttpActionResult ImportRecords()
{
    var file = HttpContext.Current.Request.Files[0];

    // Need to read parameter here
}

What is the clean/correct way to accomplish this?

Must you use $upload ? Uploading files using $http is pretty simple without the need of a separate plugin.

Factory

app.factory('apiService', ['$http', function($http){
    return {
        uploadFile: function(url, payload) {
            return $http({
                url: url,
                method: 'POST',
                data: payload,
                headers: { 'Content-Type': undefined },
                transformRequest: angular.identity
            });
        }
    };
}]);

Controller

//get the fileinput object
var fileInput = document.getElementById("fileInput");
fileInput.click();

//do nothing if there's no files
if (fileInput.files.length === 0) return;

//there is a file present
var file = fileInput.files[0];

var payload = new FormData();
payload.append("clientId", $scope.NewImport.clientId);
payload.append("file", file);

apiService.uploadFile('path/to/ImportRecords', payload).then(function(response){
    //file upload success
}).catch(function(response){
    //there's been an error
});

C# Webmethod

[HttpPost]
public JsonResult ImportRecords(int clientId, HttpPostedFileBase file)
{
    string fileName = file.FileName;
    string extension = Path.GetExtension(fileName);
    //etcc....

    return Json("horray");
}

Assuming that you are using ng-file-upload. This should work

    [Route("ImportRecords")]                
    [HttpPost] 
    public async Task<HttpResponseMessage> ImportRecords()
    {
        if (!Request.Content.IsMimeMultipartContent())
        {
            this.Request.CreateResponse(HttpStatusCode.UnsupportedMediaType);
        }

        string tempFilesPath = "some temp path for the stream"
        var streamProvider = new MultipartFormDataStreamProvider(tempFilesPath);
        var content = new StreamContent(HttpContext.Current.Request.GetBufferlessInputStream(true));
        foreach (var header in Request.Content.Headers)
        {
            content.Headers.TryAddWithoutValidation(header.Key, header.Value);
        }
        var data = await content.ReadAsMultipartAsync(streamProvider);

        //this is where you get your parameters
        string clientId = data.FormData["clientId"];                     
        ...
    }

And this is how you should be calling $upload.upload

$upload.upload({
        url: "./api/import/ImportRecords",
        method: "POST",
        data: { fileUploadObj: $scope.fileUploadObj,
                clientId: $scope.NewImport.clientId,
                file: $scope.$file
        }
            }).progress(function (evt) {
    }).success(function (data, status, headers, config) {
    }).error(function (data, status, headers, config) {
});

Hope it helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM