Как передать параметры из угловой $ upload в веб-интерфейс

0

У меня возникли проблемы с передачей параметров из моего пользовательского интерфейса в мою логику загрузки

Я настраиваю запрос на загрузку следующим образом

$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) {
});

Мой API настроен следующим образом:

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

    // Need to read parameter here
}

Каков чистый/правильный способ достичь этого?

  • 0
    В какую библиотеку входит $ upload?
Теги:
asp.net-web-api
upload

2 ответа

1

Вы должны использовать $upload? Загрузка файлов с использованием $http довольно проста без необходимости отдельного плагина.

завод

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

контроллер

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

//do nothing if there 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 been an error
});

С# Webmethod

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

    return Json("horray");
}
  • 0
    Это не то, что спросил ОП. Я не вижу, как это помогает передавать параметры с помощью ng-file-upload.
0

Предполагая, что вы используете ng-file-upload. Это должно работать

    [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"];                     
        ...
    }

И вот как вы должны вызывать $ 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) {
});

Надеюсь, поможет!

Ещё вопросы

Сообщество Overcoder
Наверх
Меню