Как отправить formData с нервом Angular -File-Upload
Я использую nervgh Angular -File-Upload at
https://github.com/nervgh/angular-file-upload
Он работает как шарм, когда я жестко кодирую preOpKey
. То, что я хотел бы сделать, - отправить preOpKey
вместе с файлом, чтобы я мог сохранить файл в соответствующей записи в базе данных.
angular -file-upload имеет fileData
в API, который я заполняю в $scope.OnPreinspectionSubmit()
, но по какой-то причине я не могу найти это значение после SaveFile()
в моем MVC-контроллере.
Мне просто нужно знать, как передать значение вместе с моим файлом, а затем получить доступ к нему в моем MVC-контроллере. Я думаю, было бы удобно отправить его в fileData
, но это не обязательно для ответа на мой вопрос.
Вот мой контроллер Angular:
var OperatorPreinspectionControllers = angular.module('OperatorPreinspectionControllers', ['angularFileUpload']);
OperatorPreinspectionControllers.controller('OperatorPreinspectionCtrl', ['$scope', '$http', 'FileUploader',
function ($scope, $http, FileUploader) {
$scope.uploader = new FileUploader({
url: pageBaseUrl + 'image/SaveFile'
});
$scope.uploader.filters.push({
name: 'imageFilter',
fn: function (item /*{File|FileLikeObject}*/, options) {
var type = '|' + item.type.slice(item.type.lastIndexOf('/') + 1) + '|';
return '|jpg|png|jpeg|bmp|gif|pdf|'.indexOf(type) !== -1;
}
});
// Send the form data to the database
$scope.OnPreinspectionSubmit = function () {
if (confirm("Are you sure you want to save this information?")) {
$http.post(pageBaseUrl + 'api/PreInspectionForm', $scope.formInformation).success(function (returnData) {
$scope.uploader.formData.push({ preOpKey: returnData });
$scope.uploader.uploadAll(); // Upload file
});
} else { }
}
}
]);
Вот мой MVC-контроллер:
public void SaveFile()
{
HttpFileCollectionBase files = Request.Files;
HttpPostedFileBase uploadedFile = files[0];
var preOpKey = 123; // ???????
// Turn the file into bytes
byte[] data;
using(Stream inputStream = uploadedFile.InputStream)
{
MemoryStream memoryStream = inputStream as MemoryStream;
if(memoryStream == null)
{
memoryStream = new MemoryStream();
inputStream.CopyTo(memoryStream);
}
data = memoryStream.ToArray();
}
PreOpManager.SaveImage(preOpKey, data, uploadedFile.FileName, uploadedFile.ContentType);
}
Спасибо,
Аарон
Ответы
Ответ 1
Единственное решение, которое до сих пор работало безупречно для меня, было:
$scope.uploader.onBeforeUploadItem = onBeforeUploadItem;
function onBeforeUploadItem(item) {
item.formData.push({your: 'data'});
console.log(item);
}
Согласно https://github.com/nervgh/angular-file-upload/issues/97#issuecomment-39248062