我无法将参数从我的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
}
完成此任务的干净/正确方法是什么?
答案 0 :(得分: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'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");
}
答案 1 :(得分:-1)
假设您正在使用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) {
});
希望它有所帮助!