Asp.编辑一个上传的图像(httppostdfilebase)在编辑Get



这是我第一次在ASP中处理文件上传。. NET MVC,我已经能够上传图像,调整大小,将其保存到服务器,重命名src字符串,以便src到图像反映产品名称(例如:"ProductImages/Original/FIFA14.jpg")。图像src也存储在数据库中,我使用Url.Action()在视图中显示图像。

对于我的编辑帖子,我希望用户能够像往常一样更改产品信息。每次用户提交表单时,之前上传的图像将被新上传的图像文件覆盖。

当我进入Edit Product Get View时,文件输入显示"no file has been selected"。我希望它显示用户在从本地计算机创建产品之前上传的图像文件。

真的有办法做到吗?怎么做到?

这是我在编辑视图中的文件输入:

       <div class="form-group">
        @Html.LabelFor(model => model.ProductImageViewModel.ImageUpload, new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            <input type="file" name="imageUpload" id="imageUpload" />
            @Html.ValidationMessageFor(model => model.ProductImageViewModel.ImageUpload)
        </div>
    </div>

Edit Get的Controller方法:

 // GET: /Product/Edit/5
    public ActionResult Edit(Guid id)
    {
        Product product = _productRepository.GetById(id);

        var productViewModel = new ProductViewModel
        {
            Id = product.Id,
            Name = product.Name,
            Description1 = product.Description1,
            Description2 = product.Description2,
            Description3 = product.Description3,
            Status = product.Status,
            Image = product.Image,
            Weight = product.Weight,
            Price = product.Price,
            ReleaseDate = product.ReleaseDate,
            Category = product.Category,
            Categories = GetCategoryDropDownListForEdit(product),
            ProductStatuses = GetStatusDropDownListForEdit(product),                
        };

        return View(productViewModel);
    }

这是我如何上传图像的创建方法:

// POST: /Product/Create
    [HttpPost]
    public ActionResult Create(ProductViewModel model, HttpPostedFileBase imageUpload)
    {
        if (UploadedFileIsValidImage(imageUpload))
        {
            byte[] productPicture = new byte[imageUpload.ContentLength];
            imageUpload.InputStream.Read(productPicture, 0, imageUpload.ContentLength);
            WebImage img = new WebImage(imageUpload.InputStream);
            img.Resize(200, 200);
            var fileName = imageUpload.FileName;
            string imageName = model.Name;
            string extension = Path.GetExtension(fileName);

            var productImageFileName = imageName + extension;
            img.FileName = productImageFileName;
            var filePathOriginal = Server.MapPath("~/ProductImages/Originals");
            var filePathThumbNail = Server.MapPath("~/ProductImages/ThumbNails");
            string savedImageFileName = Path.Combine(filePathOriginal, productImageFileName);
            img.Save(savedImageFileName);
            model.ProductImageViewModel.ImageSrc = savedImageFileName;
            model.Image = savedImageFileName;

            try
            {
                var guid = new Guid(model.SelectedCategory);
                _manager.AddProduct(
                    model.Name, model.Description1, model.Description2, model.Description3, Convert.ToDecimal(model.Price),
                    Convert.ToDateTime(model.ReleaseDate),
                    Convert.ToDouble(model.Weight), model.ProductImageViewModel.ImageSrc, guid);
                _categoryRepository.Save();
                return RedirectToAction("Index");
            }
            catch
            {
                return View();
            }
        }
        else
        {
            model.Categories = CategoryDropDownListForCreate();
            return View(model);
        }
    }

那么我怎样才能在文件输入中获得显示该产品当前上传的文件的输入呢?

您不能这样做,因为这是一个安全问题。如果你试图通过javascript设置它使用下面的代码

<script type="text/javascript">
        document.forms["form1"].elements["uploadImage"].value = "C:UsersPublicPicturesSample PicturesChrysanthemum.jpg";
</script>

如果你可以检查你的浏览器控制台,它输出错误消息说

SecurityError: The operation is insecure.

当输入类型为"file"时,不能设置其值。通常,您将在编辑视图中添加一个链接来下载当前上传的文件。

试试这种方法(不是解决方案,而是一种绕过工作的方法),

在编辑视图中,同时显示上传图像的链接和图像上传控件。如果用户想查看/预览上传的图片,可以使用图片链接。为新形象,密切取代旧形象。您可以检查这是控制器Edit方法。如果HttpPostedFileBase imageUpload不为空,则更新,否则将模型保存到数据库中。

正如其他用户已经提到的,for security reason you cannot assign the path to input control.

首先我在DB中保存了我的图像的URl,然后我不得不绕过这个问题并解决了这个

// Add this to your controller to check if the file is coming empty, If yes then I copy my previous Url to the new edited object
else if (file== null)
        {
            Product thisProduct = db.Products.Where(p => p.Id == product.Id).FirstOrDefault();
            product.Url = thisProduct.Url;
        }

    if (ModelState.IsValid)
    {
// had to use AddOrUpdate instead of Modified
        db.Set<Product>().AddOrUpdate(product);
        //db.Entry(product).State = EntityState.Modified;
        db.SaveChanges();
        return RedirectToAction("Index");
    }

最新更新