如何从角$上传参数传递给网页API
问题描述:
我在路过从我的UI参数我上传逻辑麻烦
我设置了这样
$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#WEBMETHOD
[HttpPost]
public JsonResult ImportRecords(int clientId, HttpPostedFileBase file)
{
string fileName = file.FileName;
string extension = Path.GetExtension(fileName);
//etcc....
return Json("horray");
}
+0
这不是OP要求的。我不明白这是如何帮助使用ng-file-upload传递参数。 –
答
假设你是使用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) {
});
希望它能帮助!
什么库是$上传的一部分? – jbrown