在ASP.NET中创建文件夹并上传图像的最佳方法是什么?

3

请给我一些示例代码,告诉我如何创建一个名为“pics”的文件夹并将从文件上传控件中上传的图像放入该“pics”文件夹。 如果您不想给我所有的代码,那么也可以给我一个漂亮的链接来展示如何在VB.NET(C#也可以)中完成此操作。

3个回答

13

尝试/捕获错误在你手中 :)

public void EnsureDirectoriesExist()
        {

                // if the \pix directory doesn't exist - create it. 
                if (!System.IO.Directory.Exists(Server.MapPath(@"~/pix/")))
                {
                    System.IO.Directory.CreateDirectory(Server.MapPath(@"~/pix/"));
                }

        }

        protected void Button1_Click(object sender, EventArgs e)
        {


                if (FileUpload1.HasFile && Path.GetExtension(FileUpload1.FileName) == ".jpg")
                {
                    // create posted file
                    // make sure we have a place for the file in the directory structure
                    EnsureDirectoriesExist();
                    String filePath = Server.MapPath(@"~/pix/" + FileUpload1.FileName);
                    FileUpload1.SaveAs(filePath);


                }
                else
                {
                    lblMessage.Text = "Not a jpg file";
                }


        }

鉴于最近关于过度工程的讨论,我倾向于将EnsureDirectoriesExist()的提取视为不必要的抽象的一个例子。考虑到上下文(一个stackoverflow回答),我认为可以肯定地说,你是用不着它的。 - harpo
感谢,EnsureDirectoriesExist() 可以用于文件系统的其他操作,而不仅仅是图像上传。 - roman m

2
这是我会处理的方法。
    protected void OnUpload_Click(object sender, EventArgs e)
    {
        var path = Server.MapPath("~/pics");
        var directory = new DirectoryInfo(path);

        if (directory.Exists == false)
        {
            directory.Create();
        }

        var file = Path.Combine(path, upload.FileName);

        upload.SaveAs(file);
    }

0

在文件夹内创建文件夹并上传文件

    DirectoryInfo info = new DirectoryInfo(Server.MapPath(string.Format("~/FolderName/") + txtNewmrNo.Text)); //Creating SubFolder inside the Folder with Name(which is provide by User).
    string directoryPath = info+"/".ToString();
    if (!info.Exists)  //Checking If Not Exist.
    {
        info.Create();
        HttpFileCollection hfc = Request.Files;
        for (int i = 0; i < hfc.Count; i++) //Checking how many files in File Upload control.
        {
            HttpPostedFile hpf = hfc[i];
            if (hpf.ContentLength > 0)
            {
                hpf.SaveAs(directoryPath + Path.GetFileName(hpf.FileName)); //Uploading Multiple Files into newly created Folder (One by One).
            }
        }
    }
    else
    {
        ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('This Folder already Created.');", true);
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接