使用ASP.NET MVC上载多个文件

时间:2014-05-12 09:04:36

标签: c# asp.net asp.net-mvc

我开发了一种从表单接收文件并在保存文件后从每个文件返回信息的方法。可能在互联网上有一个类似的,但我没有找到,但我还在学习c#,我喜欢建立一些方法来帮助我。

我想发布2个提议,一个是检查我是否确定,另一个原因是分享代码。

有什么建议吗?

如果你喜欢它!用它:)

我没有时间评论整个代码,抱歉! :(

方式

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

行动结果

[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 个答案:

答案 0 :(得分:1)

您可以从Request这样的对象中读取:

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

         HttpPostedFileBase file = Request.Files[fileName];

         ...
        }
    }