我正在使用Krajee FileInput通过MVC剃刀Web应用程序上传图像。效果很好,但是如果表单验证失败,如果我想返回视图,我会在表单发布后丢失图像预览。返回视图时,我可以从控制器和ViewModel填充所有其他表单元素,但是无法在表单发布后使上传的图像预览返回。在documentation中,我对此一无所获。
This post给了我一些信息,但是我无法从中获得帮助。
这是我的配置:
<script src="~/Scripts/fileinput.min.js"></script>
<script>
@{
var preview = new System.Text.StringBuilder();
var previewDelete = new System.Text.StringBuilder();
foreach (var picture in Model.Pictures)
{
preview.AppendFormat(@"'<img src=""{0}"" class=""file-preview-image"">',", picture.Url);
previewDelete.AppendFormat(@"{{url: '{0}',key: {1} }},", Url.Action("ListingPhotoDelete", "Listing", new { id = picture.ID }), picture.ID);
}
}
var $input = $("#files");
$input.fileinput({
uploadAsync: false,
showCaption: false,
showRemove: false,
showUpload: false,
maxFileCount: 5,
overwriteInitial: false,
initialPreview: [
@Html.Raw(preview.ToString())
],
initialPreviewConfig: [
@Html.Raw(previewDelete.ToString())
],
maxFileSize: 10000,
browseClass: "btn btn-primary",
allowedFileTypes: ["image"],
language: '@Context.GetPrincipalAppLanguageForRequest().ToString()'
});
在控制器中,如果表单验证失败,我尝试将文件保存在服务器上的临时位置,并使用上载的文件URL重新填充模型。然后返回视图:
//something in the form didn't validate. For example: Name == null
// Save images to temp directory and populate model with those URLs
int nextPictureOrderId2 = 0;
// Save files in temporary directory
if (files != null && files.Count() > 0)
{
foreach (HttpPostedFileBase file in files)
{
if ((file != null) && (file.ContentLength > 0) && !string.IsNullOrEmpty(file.FileName))
{
// Picture picture and get id
var picture = new Picture();
picture.MimeType = "image/jpeg";
_pictureService.Insert(picture);
await _unitOfWorkAsync.SaveChangesAsync();
// Format is automatically detected though can be changed.
ISupportedImageFormat format = new JpegFormat { Quality = 90 };
Size size = new Size(500, 0);
//https://naimhamadi.wordpress.com/2014/06/25/processing-images-in-c-easily-using-imageprocessor/
// Initialize the ImageFactory using the overload to preserve EXIF metadata.
using (ImageFactory imageFactory = new ImageFactory(preserveExifData: true))
{
var path = Path.Combine(Server.MapPath("~/images/listing/newlisting"), string.Format("{0}.{1}", picture.ID.ToString("00000000"), "jpg"));
// Load, resize, set the format and quality and save an image.
imageFactory.Load(file.InputStream)
.Resize(size)
.Format(format)
.Save(path);
var pictureModel = new PictureModel();
pictureModel.ID = picture.ID;
pictureModel.Url = ImageHelper.GetNewListingImagePath(picture.ID);
pictureModel.ListingID = listing.ID;
pictureModel.Ordering = nextPictureOrderId2;
model.Pictures.Add(pictureModel);
}
var itemPicture = new ListingPicture();
itemPicture.ListingID = listing.ID;
itemPicture.PictureID = picture.ID;
itemPicture.Ordering = nextPictureOrderId2;
_listingPictureservice.Insert(itemPicture);
nextPictureOrderId2++;
}
}
}
// return to view
return View("ListingUpdate", model);
返回视图后,图像预览不会缩放为缩略图,而是更大,在尝试删除预览时会出现JSON错误,如果我尝试再次提交表单,则不会检测到文件上传(files = 0),因此没有正确填充fileinput。
还有另一种解决方法吗?我不喜欢在返回视图之前保存到临时目录的想法,但是它还是无法正常工作。有没有一种方法可以保存和使用最初上传时最初设置的Blob网址?您可以通过使用预览缩略图上的浏览器开发工具检查元素来查看该Blob网址。