asp.net mvc的文件上传器

时间:2010-05-11 05:51:04

标签: asp.net asp.net-mvc

我有一个项目可以上传多个文件,如果有人有文件上传代码那么请分享代码。

1 个答案:

答案 0 :(得分:0)

我使用jquery MultiFile脚本 将jquery和multifile脚本引用添加到页面后,您可以向表单添加文件输入并设置class =“multi”

<input type="file" width="50" id="fileUpload" class="multi" runat="server" />

在回发时,我会遍历上传的文件,并将它们保存到服务器或云端或任何地方的目录中。

           for (int i = 0; i < Request.Files.Count; i++)
            {
                if (Request.Files[i].ContentLength > 0)
                {
                    int retVal = saveFile((HttpPostedFile)Request.Files[i]);
                    if (retVal != -1)
                        documentID.Add(retVal); // documentID is a list of ID in my sql database. This code is located in a user control for document management.
                }
            }

    // note I have a few utility methods here...
    private int saveFile(HttpPostedFile file)
    {
        if (file.ContentLength > 0)
        {
            string directory = Server.MapPath(SiteRoot + UploadURL);
            string directory_filename_uploaded = directory + file.FileName.Substring(file.FileName.LastIndexOf("\\") + 1);

            // make sure its unique so we don't overwrite.
            string directory_filename_unique = Document.GetUniqueFilename(directory_filename_uploaded);
            string filename_unique = directory_filename_unique.Substring(directory_filename_unique.LastIndexOf("\\") + 1);

            file.SaveAs(directory_filename_unique);
            return insertFile(filename_unique);
        }
        else
            return -1;
    }