【问题标题】:i have control upload file if file empty show message but if i file is not empty still show message如果文件为空,我可以控制上传文件显示消息,但如果我的文件不为空,则仍然显示消息
【发布时间】:2025-11-30 11:35:01
【问题描述】:

// 这是我的代码隐藏 处理上传文件图片,文件大小,没有文件相同

HttpFileCollection hfc = Request.Files;
            if (hfc != null)
            {
                string cekDir = string.Format("{0}\\{1}", ConfigurationManager.AppSettings["docLoc"], id_hazard_report);

                string PicDir;
                if (Directory.Exists(cekDir)) //check Folder avlalible or not
                {
                    PicDir = cekDir;
                }
                else
                {
                    DirectoryInfo di = Directory.CreateDirectory(cekDir); // create Folder
                    PicDir = cekDir;
                }

                string fullname;
                string filename;

                //FileUpload FileUpload1 = (FileUpload)FormView1.FindControl("FileUpload1");
                // string fileExt = Path.GetExtension(FileUpload1.FileName); //Get The File Extension 

//这个过程循环文件上传,这是我的问题

                for (int i = 0; i < hfc.Count; i++)
                {
                    HttpPostedFile hpf = hfc[i];
                    string fileExt = Path.GetExtension(hpf.FileName);

                    if (((CustomControls_DdlLocation)FormView1.Controls[0].FindControl("ddl_location1")).SelectedText.ToLower().Trim() == "kelanis")
                    {
                       // This my problem if file is empty... 
                        if (string.IsNullOrEmpty(hpf.FileName))
                        {

                            myfb._error("Upload harus isi");
                            return;

                    if (hpf.ContentLength > 0)
                        {
                        ///full path name to check exist or not
                        fullname = string.Format("{0}\\{1}", PicDir, Path.GetFileName(hpf.FileName.Replace(" ", "_")));
                        bool ex = File.Exists(fullname);
                        if (fileExt == (".jpg") || fileExt == (".gif") || fileExt == (".bmp") || fileExt == (".png") || fileExt == (".jpeg"))
                        {
                            if (hpf.ContentLength > 200000)/*(hpf.ContentLength > 200000)*/
                            {
                                //Session["rahmat"] = "errorLebihBesar";
                               // Response.Redirect(Request.RawUrl);
                                //ClientScript.RegisterStartupScript(Type.GetType("System.String"), "messagebox", "<script type=\"text/javascript\">alert('File Tidak boleh lebih dari 200 kb');</script>");
                                continue;
                            }


                            if (ex == true)
                            {

                                string f = Path.GetFileName(hpf.FileName.Replace(" ", "_"));
                                string[] a = new string[1];
                                a = f.Split('.');
                                filename = string.Format("{0}_{1}.{2}", a.GetValue(0), DateTime.Now.ToString("yymdHm"), a.GetValue(1));
                            }

                            else
                            {
                                filename = Path.GetFileName(hpf.FileName.Replace(" ", "_")).ToString();

                            }

                            ///full path name to store in database with new filename
                            //string[] aa = new string[1];
                            //filename = string.Format("{0}_{1}.{2}", aa.GetValue(0), DateTime.Now.ToString("yymdHm"), aa.GetValue(1));
                            fullname = string.Format("{0}\\{1}", PicDir, filename);
                            hpf.SaveAs(fullname);
                            InsertHazardDoc(id_hazard_report, filename);
                        }
                        else
                        {
                            //Session["rahmat"] = "errorFormat";
                            //Response.Redirect(Request.RawUrl);
                            // FileUpload1.Focus();
                           // ClientScript.RegisterStartupScript(Type.GetType("System.String"), "messagebox", "<script type=\"text/javascript\">alert('File Bukan Format Gambar');</script>");
                            continue;
                        }
                    }
                        }
                    }
                }
            }


            //Page.DataBind();
            //myfb._success("Hazard Report Succesfully Inserted");

            Session["rahmat"] = "success";
            Response.Redirect(Request.RawUrl);
        }
        catch (Exception ex)
        {

            myfb._error(ex.ToString());
        }

可以帮助我吗?如何解决这个问题。如果我上传文件为空,则显示消息错误,例如 myfb._error("Upload harus isi");但如果我有上传文件仍然显示消息错误 myfb._error("Upload harus isi");。我想如果有上传文件继续成功

【问题讨论】:

    标签: c# asp.net upload


    【解决方案1】:

    我不知道如何使用 HttpFileCollection hfc = Request.Files; 如果您从表单中发布,您可以这样使用。 需要改变

    HttpFileCollection  to System.Web.HttpFileCollectionBase and 
    
    System.Web.HttpPostedFileBase p;
    foreach (System.Web.HttpPostedFileBase item in hfc)
    {
        p = item;
    } 
    

    在客户端页面检查 post 方法 enctype 是否存在

    enctype="multipart/form-data"
    

    如果您使用服务器图像,请选择文件数据类型。

    【讨论】:

    • 好的先生,但是,必须专注于 hpf httppostfile 先生,这是我的问题,我不知道我写错了代码。我只想如果 hpf null 显示消息错误,否则没有消息错误就这样做。
    • if (string.IsNullOrEmpty(hpf.FileName)) { myfb._error("上传harus isi");返回; } --- 如果 (hpf.ContentLength > 0) 则缺少括号
    • 没有缺少刹车先生。我的问题 if (string.IsNullOrEmpty(hpf.FileName)) { myfb._error("Upload harus isi");返回;
    • 如果不是括号丢失错误,您需要更改我之前提到的代码。问题是 HttpFileCollection 不保存的文件数据更改代码并再次测试
    • 在我添加编码之前 if (((CustomControls_DdlLocation)FormView1.Controls[0].FindControl("ddl_location1")).SelectedText.ToLower().Trim() == "kelanis") { if (string.IsNullOrEmpty(hpf.FileName)) { myfb._error("上传 harus isi"); return;}} 我的代码正常。
    最近更新 更多