0

I've developed a method to receive file(s) from a form and return information from each file after save the file. Probably there is one on the internet that does similar, but I didn't find, however I'm still learning c# and I like build some methods to help me.

I would like to post it with 2 propose, one is check if I did ok and another reason is to share the code.

Is there any suggestion?

If you like it! use it :)

I didn't have time to comment the whole code, sorry! :(

METHOD

        public String[,] upload(IEnumerable<HttpPostedFileBase> _files, List<string> _flSupportedTypes,int _flSizeLimit, string _serverPath)
        {
            /*
             * Array Details
             * 
             * { Fields detail } 
             * [1~] [0] - Status code
             *      [1] - Status message
             *      [2] - Upload file Name
             *      [3] - New file name
             *      [4] - Virtual Path
             *      [5] - Local Path
             *      
             * { General details }
             * [0]  [0] - Status Code 
             *      [1] - Status message
             *      [2] - total fields
             *      [3] - total fields processed 
             */
            int totalFieldsUpload   = _files != null ? _files.Count() : 0;
            int countFieldsUpload   = 0;
            int countFilesUpload    = 0;
            String[,] filesResult   = new String[totalFieldsUpload + 1, 6];

            if(totalFieldsUpload == 0)
            {
                filesResult[0, 0] = "0";
                filesResult[0, 1] = "No fields";
                filesResult[0, 2] = "0";
                filesResult[0, 3] = "0";
            }
            else
            {
                filesResult[0, 0] = "1";
                filesResult[0, 1] = "OK";
                filesResult[0, 2] = totalFieldsUpload.ToString();

                if (!Directory.Exists(_serverPath))
                    Directory.CreateDirectory(_serverPath);

                foreach (var file in _files)
                {
                    bool isContentOK = false;
                    countFieldsUpload++;

                    if (file != null)
                    {
                        String newfileName  = DateTime.Now.ToFileTimeUtc() +
                                              "_" + Path.GetRandomFileName() +
                                              "." + file.FileName.ToString().Split('.').Last();

                        String localPath    = _serverPath + newfileName;
                        String virtualPath  = localPath.Replace(Request.ServerVariables["APPL_PHYSICAL_PATH"], "~/").Replace(@"\", "/");

                        if (file.ContentLength <= _flSizeLimit)
                        {
                            foreach (var type in _flSupportedTypes)
                            {
                                if (file.ContentType == type)
                                {
                                    file.SaveAs(localPath);
                                    isContentOK = true;

                                    countFilesUpload++;

                                    break;
                                }
                                else
                                    isContentOK = false;

                            }

                            filesResult[countFieldsUpload, 0] = "1";
                            filesResult[countFieldsUpload, 1] = isContentOK ? "OK" : "ContentType Failed";
                            filesResult[countFieldsUpload, 2] = file.FileName;
                            filesResult[countFieldsUpload, 3] = newfileName;
                            filesResult[countFieldsUpload, 4] = virtualPath;
                            filesResult[countFieldsUpload, 5] = localPath;
                        }
                        else
                        {
                            filesResult[countFieldsUpload, 0] = "0";
                            filesResult[countFieldsUpload, 1] = "Size Failed";
                            filesResult[countFieldsUpload, 2] = file.FileName;
                        }

                    }
                    else
                    {
                        filesResult[countFieldsUpload, 0] = "0";
                        filesResult[countFieldsUpload, 1] = "Field empty";
                    }
                }

                filesResult[0, 3] = countFilesUpload.ToString();
             }

             return filesResult;              
        }

HTML

@using (Html.BeginForm("ActionTest", "Controller", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    @Html.AntiForgeryToken()
    Html.EnableClientValidation(false);
    <div class="form-group">
        <label for="photo">Photo:</label>
        <input type="file" name="photo[0]" id="photo_0">
        <input type="file" name="photo[1]" id="photo_1">
        <input type="file" name="photo[2]" id="photo_2">
        <input type="submit" />
    </div>
}

ACTION RESULT

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult ActionTest(IEnumerable<HttpPostedFileBase> photo)
{
    List<string>    supportedTypes  = new List<string>() { "image/jpeg", "image/gif", "image/png" };
    String          serverPath      = Server.MapPath("/") + ConfigurationManager.AppSettings["imgTmpUploadPath"].ToString();
    String[,]       filesResult     = upload(photo, supportedTypes, 1048576, serverPath);

    return View();
}

1 Answer 1

1

You can read from Request object like this:

[HttpPost]
    public ActionResult Page2(FormCollection objCollection)
    {
        foreach (string fileName in Request.Files)
        {

         HttpPostedFileBase file = Request.Files[fileName];

         ...
        }
    }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.