开发者

Fetching Fileupload value from FormCollection values in mvc

I am trying to check if the file is selected in the fileupload in mvc using Form collection but the formvalues is always null , fileupload is not passing the uploaded file name to formcollection , below is the code:

   public ActionResult Create(FormCollection formValues,IEnumerable<HttpPostedFileBase> files, Venue venue)
    {
        string[] images = { "", "" };
        int i = 0;
     //   string smallImage;
      //  string largeImage;
        foreach (HttpPostedFileBase file in files)
        {
            if (file != null)
            {
                if (i == 0)
                {

                    string newFileName = string.Format("{0}{1}", Guid.NewGuid().ToString(), Path.GetExtension(file.FileName));
                    var fileName = Path.GetFileName(file.FileName);
                    var path = Path.Combine(Server.MapPath("~/Content/images/content/"), fileName);
                    file.SaveAs(path);
                    Helpers.ImageHelpers.ResizeImage(newFileName, path, "/Content/images/content/", 162, 105);
                    images[0] = newFileName;
                    venue.ImageSmall = images[0];
                //    smallImage = "selected";
                }

                if (i == 1)
                {

                    str开发者_JAVA百科ing newFileName = string.Format("{0}{1}", Guid.NewGuid().ToString(), Path.GetExtension(file.FileName));
                    var fileName = Path.GetFileName(file.FileName);
                    var path = Path.Combine(Server.MapPath("~/Content/images/content/"), fileName);
                    file.SaveAs(path);
                    Helpers.ImageHelpers.ResizeImage(newFileName, path, "/Content/images/content/", 212, 240);
                    images[1] = newFileName;
                    venue.ImageLarge = images[1];
                 //   largeImage = "selected";
                }

            }
            i++;
        }

        if (string.IsNullOrEmpty(formValues["files1"]) || string.IsNullOrEmpty(formValues["files2"])  )
        {

            ModelState.AddModelError("files", "Please upload a file");
        }

      <td>
                        <div class="editor-field">
                            <input type="file" name="files" id="files1" style="color:White" />


                            </div>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            Detail Image
                        </td>
                        <td>
                        <div class="editor-field">
                            <input type="file" name="files" id="files2" style="color:White"/>


                            </div>
                        </td>
                    </tr>

Fetching Fileupload value from FormCollection values in mvc


  1. You are using wrong IDs ("files1" and "files2" in html, but "file1" and "file2" in the code)

  2. Even if you used correct IDs, this code wouldn't work because form parameters are named using values from "name" attribute. So, you have to create an unique name for each input tag in your html and then use these names in code.

In case you want to loop over files. You can give them the same id and then use Request.Files property in controller method on server side.


What I am currently using to handle file up loads from a user via a multipart form is the following code.

The clincher for me was the fact that I don't have Models so much as I have a BusinessLogicLayer.dll file which serves as my Models with the exception of some rare exceptions that one of the programmers on my project ran into.

This part is the Form form the View with a good chunk of the code removed for brevity save for what pertains to this question.

<form id="payInfo" name="payInfo" action="@Url.Action("ShipMethod", "CheckOut")" method="post" enctype="multipart/form-data">

    <div id="12" class="custom-control custom-radio">
        <input type="radio" class="custom-control-input" id="payInvoice" name="payMethod" required />
        <!--on submit if this is selected, the customer will see a thank you as well as instructions on when/how the invoice will be available.-->
        <label class="custom-control-label" for="payInvoice">Send Invoice</label>
    </div>

    <div id="invoice" class="collapse img-thumbnail">                               
        <p class="h6 mb-2">You can provide the PO number on your Purchase Order, or you can accept the generated PO number that we have provided for you.</p>

        <div class="form-group row">
            <label for="invoicePO" class="col-2 col-form-label font-weight-bold">po number: </label>
            <div class="col-4"><!--Invoice name/prefill--></div>
            <div class="col-6">&nbsp;</div>
        </div>

        <div class="form-group row">
            <label for="POfile" class="col-2 col-form-label font-weight-bold">PO PDF: </label>
            <div class="col-4"><input type="file" class="form-control-file" id="POfile" name="POfile" /></div>
            <div class="col-6">&nbsp;</div>
        </div>
    </div>

    <button class="btn btn-secondary btn-lg btn-block" type="submit">Continue To Shipping</button>

</form>

From there the form gets processed by the Controller (With help of a private method) as seen in the next bit of code. (Also edited for brevity and pertinence)

public ActionResult ShipMethod(FormCollection fc)
{
    // Gets the file(s) uploaded by the user using the form
    HttpFileCollectionBase file = Request.Files;

    // In this point I'm only looking for 1 file as that is all the user is allowed to upload
    if (file.Count == 1)
    {
        // This being the reference to the private method mentioned earlier
        /* We're passing the customer's cart and 
         * the file variable that was filled above as the Cart will be constant 
         * until the user confirms their purchase, making it ideal to hold on to 
         * the file details until the purchase is actually processed in the 
         * last step of the check out process. */
        GetPO(_cart, file);
    }
}

Below is the code for the method that ACTUALLY handles the uploaded file.

private void GetPO(Cart _cart, HttpFileCollectionBase file)
{
    // Setting up a regEx to help me to restrict the kinds of files the user can upload to our server
    string fileRegEx = @"^.+\.((pdf))$";
    Regex regex = new Regex(fileRegEx, RegexOptions.IgnoreCase);

    // This gets just the filename and its extension instead of the fully qualified name
    // which we don't want when working with the RegEx comparison
    string fileName = Path.GetFileName(file[0].FileName);

    if (regex.IsMatch(fileName))
    {
        // If we're here, then the file name indicates that the file is a PDF
        if (file != null && file[0].ContentLength > 0)
        {
            // If we're here then there is actual substance to the file that was uploaded
            // So we'll need to make a byte array to temporarily 
            // hold the file contents before storage
            byte[] upload = new byte[file[0].ContentLength];

            // Get the File contents
            file[0].InputStream.Read(upload, 0, file[0].ContentLength);

            // Now that we have the contents, pass those contents on 
            // to the object that will hold onto it till the purchase 
            // is in the final stage of processing
            _cart.POContent = upload;

            // This section will get the other pertinent data pieces for storage
            // Get the index of the last period in the file name
            int lastIndex = fileName.LastIndexOf('.');
            // Get the file extension
            string ext = fileName.Substring(++lastIndex);

            // Get the POName and POContentType
            if (ext.ToLower() == "pdf")
            {
                // Get the Media Content Type
                _cart.POContentType = MediaContentType.PDF;
                // Get the name of the file without the extension
                _cart.POName = fileName.Remove(--lastIndex);
            }
            else
            {
                // TODO: Error handling for the wrong file extension
            }
        }
    }
    else
    {
        // TODO: Set up Error Handling for invalid or empty file
    }
}

This round of code isn't completely ready for public consumption, but I know that this much DOES work in conjunction with the BLL and DAL we have.

This was a solution we had for allowing corporate customers to upload purchasing orders when they ordered from the website. If you wanted to loop through your files, you could go back up to the second code blurb and after checking that you have files, be able to loop through them in for processing.

This is done with ASP, MVC 4, .NET Framework 4.6.1

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜