Handling Multiple Optional File Uploads with C# - .NET

元气小坏坏 提交于 2019-12-11 10:03:59

问题


I have 8 different files I'd like to upload.

Currently I'm using the code below. The following is just a snippet for uploading the first 2 files. It works great, but is soon going to start getting ugly as I start to add more and more file upload fields.

WebForm: <p> Thumb 1:<br /> <asp:FileUpload ID="img1sml" type="file" name="img1sml" runat="server" /> </p> <p> Image 1:<br /> <asp:FileUpload ID="img1" type="file" name="img1" runat="server" /> </p>...

CodeBehind: if (!string.IsNullOrWhiteSpace(img1sml.FileName)) { img1sml.PostedFile.SaveAs(Server.MapPath("~/Images/" + img1sml.FileName)); img1.PostedFile.SaveAs(Server.MapPath("~/Images/" + img1.FileName)); // Create command comm = new SqlCommand("INSERT INTO news (title, img1sml, img1, img1sml) VALUES (@Title, @img1sml, @img1)", conn); // Add command parameters

I'd like to be able to test (in an efficient way) if each of the 8 file upload fields is empty or not. If they are empty I'd like to skip the file upload and db insertion and move to the next file.

How would you recommend I do this?

Many many thanks for any guidance with this.


回答1:


You can loop through a collection of posted files in the request object, called Request.Files

    foreach (string key in Request.Files)
    {
        HttpPostedFile file = Request.Files[key];
        if (file.ContentLength != 0)
        {
          file.SaveAs(Server.MapPath("~/Images/" + file.FileName));
        }
    }


来源:https://stackoverflow.com/questions/6145817/handling-multiple-optional-file-uploads-with-c-sharp-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!