简体   繁体   中英

Upload Image ASP.NET MVC

Hey I want to upload picture and save that picture to a folder, and save the name of that picture to DB in addition I am also using model binding for other fields of form. Here is the code in this HttpPostedFileBase file receives null I am also using enctype = "multipart/form-data" in my form.

public ActionResult UmrahPackage(PackagesModel model, , HttpPostedFileBase file)
    {
        try
        {
            if (model.ID == 0)
            {
                String fileName = "";
                Pakage pkg = new Pakage();
                pkg.Title = model.Title;
                pkg.PackageDetail = model.PackageDetail;
                pkg.Duration = model.Duration;

                if (file != null)
                {
                    fileName = System.Guid.NewGuid().ToString() + System.IO.Path.GetExtension(file.FileName);
                    string physicalPath = Server.MapPath("~/Images/Uploads" + fileName);
                    // save image in folder
                    file.SaveAs(physicalPath);
                }}

In addition I am also trying this but I am not be able to understand that how to save image in folder I mean the object instance before SaveAs -> file

if (Request.Files.Count > 0 && String.IsNullOrEmpty(Request.Files[0].FileName) == false)
                {
                    HttpPostedFileBase file;
                    fileName = System.Guid.NewGuid().ToString() + System.IO.Path.GetExtension(Request.Files[0].FileName);
                    string physicalPath = Server.MapPath("/uploads/profileimages/") + fileName;
                    file.SaveAs(physicalPath);
                }

My form looks like,

    @using (Html.BeginForm("UmrahPackage", "Home", FormMethod.Post, new { enctype = "multipart/form-data"}))
                {
                    @Html.HiddenFor(model => model.ID)

                    <label>Title:</label>
                    @Html.TextBoxFor(model => model.Title)

                    <label>Upload Image</label>
                    <input type="file" id="imgInp">

                    <button type="submit" >Create</button>
                }

Kindly help me, Thanks.

Your input element name attribute value should match with your parameter name

Since your HttpPostedFileBase parameter name is file , give the same name for your file input.

<input type="file" name="file" />

Now when the form is submitted, model binder will be able to map your submitted form data to your parameter named file

I also suggest you to use Path.Combine instead of string concatenation.

string physicalPath = Path.Combine(Server.MapPath("~/Images/Uploads"), fileName);

I had referred to this link to fix the problem of overwriting previously selected files. But this method has led to another problem. The pictures selected were duplicated. Meaning that if I choose 3 pictures, it would save 6. The following code is my javascript

            <input type="file" id="files" name="files" class="btn" style="color:white" multiple />


function previewImages() {
    linebreak = document.createElement("br");
    var preview = document.querySelector('#preview');
    if (this.files) {
        [].forEach.call(this.files, readAndPreview);
    }
    function readAndPreview(file) {
        // Make sure `file.name` matches our extensions criteria
        if (!/\.(jpe?g|png|gif)$/i.test(file.name)) {
            $('#files').val('');
            return alert(file.name + " is not an image");

        } else if (file.size > 4194304) {
            $('#files').val('');

            return alert(file.name + "is larger than 4MB");

        } else {
            var reader = new FileReader();
            reader.addEventListener("load", function () {
                var image = new Image();
                image.height = 100;
                image.title = file.name;
                image.src = this.result;
                preview.append(image.title);
                preview.appendChild(image);
            });
            reader.readAsDataURL(file);
        }
    }
}
//document.querySelector('#files').addEventListener("change", previewImages);
$(document).on('change', 'input[type="file"][multiple]', function () {
    var $this = $(this);
    $this.clone().insertAfter($this);
    $this.hide();

});

$(document).on('change', 'input[type="file"][multiple]', previewImages);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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