FileUpload未上传所有图片

时间:2022-11-04 07:56:49

I'm working on a project in which I've to upload multiple files using FileUpload control:

我正在开发一个项目,我将使用FileUpload控件上传多个文件:

I've a button to save image files as like this:

我有一个保存图像文件的按钮,如下所示:

protected void btnSave_Click(object sender, EventArgs e)
{
    if (fuImage.HasFiles)
    {
        foreach (var file in fuImage.PostedFiles)
        {
            UploadFile("Images",fuImage);
        }
    }

}

And there is a method which I use to upload/save-as the file into folder as like this:

并且我有一种方法可以将文件上传/保存为文件夹,如下所示:

private void UploadFile(string FolderName, FileUpload fu)
{
    string FolderPath = "~\\" + FolderName;

    DirectoryInfo FolderDir = new DirectoryInfo(Server.MapPath(FolderPath));
    if (!FolderDir.Exists)
    {
        FolderDir.Create();
    }

    string FilePath = Path.Combine(Server.MapPath(FolderPath), fu.FileName);
    if (!File.Exists(FilePath))
    {
        fu.SaveAs(FilePath);
    }
}

The problem that I'm facing is - only one image file is uploads instead of uploading all images as like: FileUpload未上传所有图片

我面临的问题是 - 只上传一个图像文件而不是像上传所有图像:

Any help will be really appreciated!

任何帮助将非常感谢!

1 个解决方案

#1


0  

You have an error in your code. Here is a fixed code.

您的代码中有错误。这是一个固定的代码。

First make sure that you build the page on asp.net 4.5 or newer

首先确保您在asp.net 4.5或更高版本上构建页面

web.config

web.config中

<compilation debug="true" targetFramework="4.6.1" urlLinePragmas="true"/>

Next your .cs.

接下来你的.cs。

protected void btnSave_Click(object sender, EventArgs e)
{
    if (fuImage.HasFiles)
    {
        foreach (HttpPostedFile file in fuImage.PostedFiles) //be explicit
        //Note that var file is HttpPostedFile
        {
            UploadFile("Images",file); //not fuImage
        }
    }
}

private void UploadFile(string FolderName, HttpPostedFile fu)//FileUpload gives single file
{
    string FolderPath = "~/" + FolderName; // \\ is not the best choice
    //your remaining code works and is skipped for brevity

}

#1


0  

You have an error in your code. Here is a fixed code.

您的代码中有错误。这是一个固定的代码。

First make sure that you build the page on asp.net 4.5 or newer

首先确保您在asp.net 4.5或更高版本上构建页面

web.config

web.config中

<compilation debug="true" targetFramework="4.6.1" urlLinePragmas="true"/>

Next your .cs.

接下来你的.cs。

protected void btnSave_Click(object sender, EventArgs e)
{
    if (fuImage.HasFiles)
    {
        foreach (HttpPostedFile file in fuImage.PostedFiles) //be explicit
        //Note that var file is HttpPostedFile
        {
            UploadFile("Images",file); //not fuImage
        }
    }
}

private void UploadFile(string FolderName, HttpPostedFile fu)//FileUpload gives single file
{
    string FolderPath = "~/" + FolderName; // \\ is not the best choice
    //your remaining code works and is skipped for brevity

}