[英]How to pass multiple type of parameters in web api from angularjs?
[英]How to pass parameters from angular $upload to web api
我無法將參數從用戶界面傳遞到上傳邏輯
我正在這樣設置上傳請求
$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
}
什么是干凈/正確的方法來完成此操作?
您必須使用$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'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#Web方法
[HttpPost]
public JsonResult ImportRecords(int clientId, HttpPostedFileBase file)
{
string fileName = file.FileName;
string extension = Path.GetExtension(fileName);
//etcc....
return Json("horray");
}
假設您正在使用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) {
});
希望能幫助到你!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.