开发者

Handling Multiple Optional File Uploads with C# - .NET

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 SqlComman开发者_运维技巧d("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.


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));
        }
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜