C# 如何使用Web API随viewModel发送文件或如何使用临时数据保存
我已经阅读了许多有类似问题的stackoverflow帖子以及一些博客,但我仍然不确定如何解决我的问题:( 我有angularJS指令,允许将文件上载到服务器。代码如下:C# 如何使用Web API随viewModel发送文件或如何使用临时数据保存,c#,angularjs,repository,ng-file-upload,C#,Angularjs,Repository,Ng File Upload,我已经阅读了许多有类似问题的stackoverflow帖子以及一些博客,但我仍然不确定如何解决我的问题:( 我有angularJS指令,允许将文件上载到服务器。代码如下: [HttpPost] [Route("UploadFile")] public async Task<HttpResponseMessage> UploadFile() { // Check if the request contains m
[HttpPost]
[Route("UploadFile")]
public async Task<HttpResponseMessage> UploadFile()
{
// Check if the request contains multipart/form-data.
if (Request.Content.IsMimeMultipartContent("form-data"))
{
try
{
var resultOut = new List<FileUploadResult>();
var streamProvider = new MultipartMemoryStreamProvider();
streamProvider = await Request.Content.ReadAsMultipartAsync(streamProvider);
foreach (
var item in
streamProvider.Contents.Where(c => !string.IsNullOrEmpty(c.Headers.ContentDisposition.FileName))
)
{
FileUploadResult file = new FileUploadResult()
{
FileName = item.Headers.ContentDisposition.FileName,
// Content = fileBytes, // No need to pass the info back as we're not going to read it save it yet
Key = Guid.NewGuid().ToString(),
Type = item.Headers.ContentDisposition.DispositionType
};
resultOut.Add(file);
//using (Stream stFileSource = new MemoryStream(await item.ReadAsByteArrayAsync())) {
// byte[] fileBytes;
// fileBytes = new Byte[stFileSource.Length];
// stFileSource.Read(fileBytes, 0, Convert.ToInt32(stFileSource.Length));
// FileUploadResult file = new FileUploadResult()
// {
// FileName = item.Headers.ContentDisposition.FileName,
// // Content = fileBytes, // No need to pass the info back as we're not going to read it save it yet
// Key = Guid.NewGuid().ToString(),
// Type = item.Headers.ContentDisposition.DispositionType
// };
// resultOut.Add(file);
//}
}
return Request.CreateResponse(HttpStatusCode.OK, resultOut.ToArray());
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.ToString());
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
}
else
{
return Request.CreateResponse(HttpStatusCode.BadRequest);
}
}
[HttpPost]
[路由(“上传文件”)]
公共异步任务上载文件()
{
//检查请求是否包含多部分/表单数据。
if(Request.Content.IsMimeMultipartContent(“表单数据”))
{
尝试
{
var resultOut=新列表();
var streamProvider=新的MultipartMemoryStreamProvider();
streamProvider=wait Request.Content.ReadAsMultipartAsync(streamProvider);
弗雷奇(
风险值项目
streamProvider.Contents.Where(c=>!string.IsNullOrEmpty(c.Headers.ContentDisposition.FileName))
)
{
FileUploadResult文件=新FileUploadResult()
{
FileName=item.Headers.ContentDisposition.FileName,
//Content=fileBytes,//不需要将信息传回,因为我们还不打算读取它并保存它
Key=Guid.NewGuid().ToString(),
类型=item.Headers.ContentDisposition.DispositionType
};
resultOut.Add(文件);
//使用(Stream stFileSource=new MemoryStream(wait item.ReadAsByteArrayAsync())){
//字节[]文件字节;
//fileBytes=新字节[stFileSource.Length];
//读取(fileBytes,0,Convert.ToInt32(stFileSource.Length));
//FileUploadResult文件=新FileUploadResult()
// {
//FileName=item.Headers.ContentDisposition.FileName,
////Content=fileBytes,//不需要将信息传回,因为我们还不打算读取它并保存它
//Key=Guid.NewGuid().ToString(),
//类型=item.Headers.ContentDisposition.DispositionType
// };
//resultOut.Add(文件);
//}
}
return Request.CreateResponse(HttpStatusCode.OK,resultOut.ToArray());
}
捕获(例外情况除外)
{
System.Diagnostics.Debug.WriteLine(例如ToString());
返回请求.CreateResponse(HttpStatusCode.BadRequest);
}
}
其他的
{
返回请求.CreateResponse(HttpStatusCode.BadRequest);
}
}
指令还将文件数组保存到属性中。我的用户表单允许删除一些文件/添加更多文件,然后我希望保存表单中的信息(有点复杂的视图模型)与文件一起。到目前为止,我还无法解决这个问题。我在这里看到的一种可能性是使用Repository以UploadFile方法将文件保存到数据库中。但是,我更愿意将其保存到某个临时表(例如#FileInfo表)而不是实际的表中。或者有一种保存文件的方法(带有二进制内容)存储到某个内存对象中,这样我就可以在准备保存模型数据时取回该内容了?您可以展示临时存储库的实现,或者为我的困境提供一些其他想法吗?首先,您的指令需要使用“多部分/表单数据”创建post请求 查阅参考资料 然而,我们过去常常这样做
angular
.module('app', ['angularFileUpload'])
.controller('AppController', function($scope, FileUploader) {
$scope.uploader = new FileUploader(
{
url: 'Your/upload/url',
headers: {
'autorization': 'Bearer token if you need it'
},
onProgressItem: function () {
...
},
onSuccessItem: function (opt, data) {
...
},
onErrorItem: function (opt) {
...
}
});
//you may want to wrap the following in an event
var uploadItem = $scope.uploader.queue[uploader.queue.length - 1];
uploadItem.formData.push({
someData: "someData",
moreData: "moreData"
});
uploadItem.upload();
uploadItem.formData = [];
});
然后在控制器中,您可以执行以下操作以检索所需内容:
//your request
var request = HttpContext.Current.Request;
//your fields
var someData = request.Form["someData"];
var moreData = request.Form["moreData"];
//your file
var file = request.Files["file"];
首先,您的指令需要使用“多部分/表单数据”创建post请求 查阅参考资料 然而,我们过去常常这样做
angular
.module('app', ['angularFileUpload'])
.controller('AppController', function($scope, FileUploader) {
$scope.uploader = new FileUploader(
{
url: 'Your/upload/url',
headers: {
'autorization': 'Bearer token if you need it'
},
onProgressItem: function () {
...
},
onSuccessItem: function (opt, data) {
...
},
onErrorItem: function (opt) {
...
}
});
//you may want to wrap the following in an event
var uploadItem = $scope.uploader.queue[uploader.queue.length - 1];
uploadItem.formData.push({
someData: "someData",
moreData: "moreData"
});
uploadItem.upload();
uploadItem.formData = [];
});
然后在控制器中,您可以执行以下操作以检索所需内容:
//your request
var request = HttpContext.Current.Request;
//your fields
var someData = request.Form["someData"];
var moreData = request.Form["moreData"];
//your file
var file = request.Files["file"];
看起来像是TempData的作业: ASP.NET MVC中的TempData基本上是从 TempDataDictionary.TempData作为后续HTTP请求保留 与其他选项(ViewBag和ViewData)相反,这些选项仅用于 当前请求。因此,可以使用tempdata在 控制器操作以及重定向 例如:
//Controller Action 1 (TemporaryEmployee)
public ActionResult TemporaryEmployee()
{
Employee employee = new Employee
{
EmpID = "121",
EmpFirstName = "Imran",
EmpLastName = "Ghani"
};
TempData["Employee"] = employee;
return RedirectToAction("PermanentEmployee");
}
//Controller Action 2(PermanentEmployee)
public ActionResult PermanentEmployee()
{
Employee employee = TempData["Employee"] as Employee;
return View(employee);
}
看起来像是TempData的作业: ASP.NET MVC中的TempData基本上是从 TempDataDictionary.TempData作为后续HTTP请求保留 与其他选项(ViewBag和ViewData)相反,这些选项仅用于 当前请求。因此,可以使用tempdata在 控制器操作以及重定向 例如:
//Controller Action 1 (TemporaryEmployee)
public ActionResult TemporaryEmployee()
{
Employee employee = new Employee
{
EmpID = "121",
EmpFirstName = "Imran",
EmpLastName = "Ghani"
};
TempData["Employee"] = employee;
return RedirectToAction("PermanentEmployee");
}
//Controller Action 2(PermanentEmployee)
public ActionResult PermanentEmployee()
{
Employee employee = TempData["Employee"] as Employee;
return View(employee);
}
我的问题是有点倒退。我的模型的主窗体有另一个指令显示这些上传的文件(文件名)现在是时候保存信息了。我确实有一个文件数组-我需要再次实例化一个上传程序吗?只要你能把所有的信息和你需要的所有元数据放到一个地方,你就可以在那里生成一个上传程序,然后上传它们。我将继续这个想法。我们'我们在应用程序中使用这个。因此,我将把'Upload'添加到我的控制器,并在代码中实例化它,看看它是如何工作的。我的问题是有点倒退。我的模型的主窗体有另一个指示,显示这些上传的文件(文件名)现在是时候保存信息了。我确实有一个文件数组-我需要再次实例化一个上传程序吗?只要你能把所有需要的信息和元数据放到一个地方,你就可以在那里生成一个上传程序,然后上传它们。我马上就去