使用上传文件的新实现,即IFormFile。我创建了一个视图模型并将其映射到模型上,但是,我在视图模型的ImageFile属性上获得了一个空值。在插入记录时,我使用AngularJS来防止它重新加载。以下是我的观点和控制器。
public string CreateNewProduct([FromBody] ProductViewModel _product)
{
var imgFile = _product.ImageFile;
var fileName = ContentDispositionHeaderValue.Parse(imgFile.ContentDisposition).FileName.Trim('"');
var targetDirectory = Path.Combine(environment.WebRootPath, string.Format("Common\\Images\\"));
var savePath = Path.Combine(targetDirectory, fileName);
imgFile.CopyTo(new FileStream(savePath, FileMode.Create));
Products product = new Products
{
ItemCode = _product.ItemCode,
FileName = fileName,
FilePath = savePath
};
context.Products.Add(product);
context.SaveChanges();
return "";
}
这是我在对话框中的视图。
<div class="modal" role="dialog" id="addItemDialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h3 class="text-info">Add New Item</h3>
</div>
<div class="modal-body">
<form id="newproductform" class="form-horizontal" role="form" enctype="multipart/form-data">
<div class="form-group">
<span class="col-sm-3 control-label">Item Code</span>
<div class="col-sm-6">
<input type="text" class="form-control input-sm" ng-model="ItemCode" />
</div>
</div>
<div class="form-group">
<span class="col-sm-3 control-label">Image</span>
<input type="file" name="file" accept="image/*" onchange="angular.element(this).scope().selectFileforUpload(this.files)" required />
<span class="error" ng-show="(f1.file.$dirty || IsFormSubmitted) && f1.file.$error.required">Image required!</span>
</div>
</form>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-success" ng-click="InsertProduct()">Submit</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
我刚刚使用了提交按钮,但我仍然在视图模型上的ImageFile属性上获得空值。
这是我的观点模型。
public class ProductViewModel
{
public string ItemCode { get; set; }
//[FileExtensions(Extensions = "jpg/jpeg")]
public IFormFile ImageFile { get; set; }
}