处理与C#多个可选文件上传 - .NET [英] Handling Multiple Optional File Uploads with C# - .NET

查看:181
本文介绍了处理与C#多个可选文件上传 - .NET的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的 8 不同的文件,我想上传

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

目前我使用下面的code。下面只是上传的第2个文件的一个片段。它的伟大工程,但很快就要开始越来越丑,因为我开始添加越来越多的文件上传领域。

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.

Web窗体:
< P>
  拇指1:< BR />
    < ASP:文件上传ID =img1sml类型=文件名称=img1sml=服务器/>
  &所述; / P>
  &所述p为H.;
  图1:< BR />
    < ASP:文件上传ID =IMG1类型=文件名称=IMG1=服务器/>
  < / P> ...

codeBehind:(!string.IsNullOrWhiteSpace(img1sml.FileName)) 如果
            {
                img1sml.PostedFile.SaveAs(使用Server.Mappath(〜/图片/+ img1sml.FileName));
                img1.PostedFile.SaveAs(使用Server.Mappath(〜/图片/+ img1.FileName));
                // Create命令
                COMM =新的SqlCommand(插入新闻(标题,img1sml,IMG1,img1sml)VALUES(@Title,@ img1sml,@​​ IMG1),conn);在
                //添加命令参数

我希望能够测试(一种有效的方式),如果每个8的文件上传的字段是空。如果它们是空的,我想跳过文件的上传和数据库插入和移动到下一个文件。

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.

如何建议我这样做呢?

很多很多的感谢与此任何指导意见。

Many many thanks for any guidance with this.

推荐答案

您可以通过在请求对象发布文件集合环,称为Request.Files

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

这篇关于处理与C#多个可选文件上传 - .NET的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆