简体   繁体   English

Asp.Net MVC在“编辑获取”中编辑上传的图像(HTTPPostedFileBase)

[英]Asp.Net MVC Edit an uploaded image (HTTPPostedFileBase) in Edit Get

This is the first time I'm working with file uploads in ASP.NET MVC, and I've been able to upload an image, resize it, save it to the server, rename the src-string so the src to image reflect the products name (for example: "ProductImages/Original/FIFA14.jpg"). 这是我第一次在ASP.NET MVC中处理文件上传,并且能够上传图像,调整大小,将其保存到服务器,重命名src字符串,以便图像的src反映产品名称(例如:“ ProductImages / Original / FIFA14.jpg”)。 The image src is also stored in the database which I use to Display the images in the view with an Url.Action(). 图像src也存储在数据库中,该数据库用于通过Url.Action()在视图中显示图像。

For my edit post, I want the user to be able to change the product information as usual. 对于我的编辑帖子,我希望用户能够像往常一样更改产品信息。 And everytime a user submits the form, the image that has been uploaded before will be overwritten with the new imagefile which has been uploaded. 并且,每当用户提交表单时,之前已上传的图像将被已上传的新图像文件覆盖。

When I enter the Edit Product Get View, the file input says "no file has been chosen". 当我进入“编辑产品获取视图”时,文件输入显示“未选择文件”。 I want it to show the image file that the user uploaded before when he created the product from his local computer. 我希望它显示用户从本地计算机创建产品之前上传的图像文件。

Is there really a way to that, and how? 真的有办法吗?如何?

Here's my File input in Edit View: 这是我在“编辑视图”中的文件输入:

       <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>

The Controller method for Edit Get: 用于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);
    }

This is how I upload the Image in the Create Method: 这是我在Create方法中上传图像的方式:

// 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);
        }
    }

So how can I get the input to show the current uploaded file for this product in the file input? 那么,如何在文件输入中获取输入以显示该产品的当前上传文件?

You cannot do so as it is a security issue. 您不能这样做,因为这是一个安全问题。 If you try to set it through javascript with the following piece of code 如果您尝试使用以下代码通过javascript进行设置

<script type="text/javascript">
        document.forms["form1"].elements["uploadImage"].value = "C:\Users\Public\Pictures\Sample Pictures\Chrysanthemum.jpg";

</script>

If you can check your browser console, it outputs error message saying that 如果您可以检查浏览器控制台,则会输出错误消息,指出

SecurityError: The operation is insecure.

When the type of the input is "file" you can't set the value of it. 当输入类型为“文件”时,您无法设置其值。 Usually you will add a link to download the current uploaded file in the edit view. 通常,您会在编辑视图中添加一个链接以下载当前上传的文件。

Try this way (not solution but a way around to work), 尝试这种方式(不是解决方案,而是一种解决方法),

In Edit View, show a link of uploaded image and an image upload control side by side. 在“编辑视图”中,并排显示上载图像的链接和图像上载控件。 If user want to see/preview the uploaded image, can use link of image. 如果用户想查看/预览上传的图像,可以使用图像链接。 For new image which intimately replace the old image. 对于新图像,可以直接替换旧图像。 You can check this is controller Edit method. 您可以检查这是控制器的Edit方法。 If HttpPostedFileBase imageUpload is not null then update, otherwise just save the model into database. 如果HttpPostedFileBase imageUpload不为null,则进行更新,否则将模型保存到数据库中。

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

First i Saved the URl of my image in DB, then I had to go around the problem and solved it with this 首先,我将图像的URl保存到DB中,然后我不得不解决该问题并通过此方法解决了该问题

// 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");
    }

我在Google上展示了成千上万的帖子。所有这些都是在浪费时间或毫无用处,没有博客可以告诉您如何在Web应用程序的图像控件中编辑或显示图像。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM