// 如果我上传 1.chicken.jpg 180kb 2.chicken.pdf 但 chicken.pdf 跟随插入到数据库,为什么这段代码不起作用

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];

                        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 (hpf == (".jpg") || fileExt == (".gif") || fileExt == (".bmp") || fileExt == (".png") || fileExt == (".jpeg"))
                            {
                                if(FileUpload1.FileBytes.Length > 200000)
                                {

                                    ClientScript.RegisterStartupScript(Type.GetType("System.String"), "messagebox", "<script type=\"text/javascript\">alert('File Tidak boleh lebih dari 200 kb');</script>");
                                    break;  
                                }


                                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); //save as
                            InsertHazardDoc(id_hazard_report, filename);
                            }
                            else
                            {
                                FileUpload1.Focus();
                                ClientScript.RegisterStartupScript(Type.GetType("System.String"),"messagebox", "<script type=\"text/javascript\">alert('File Bukan Format Gambar');</script>");
                                break;
                            }
                        }
                     //}

                    }
                }
                    #endregion

                    //Page.DataBind();

                    myfb._success("Hazard Report Succesfully Inserted");

            }
            catch (Exception ex)
            {
                myfb._error(ex.ToString());
            }

        }

// 如果我上传 1.chicken.jpg 180kb 2.chicken.pdf 但 chicken.pdf 跟随插入到数据库,为什么这段代码不起作用


在这里你定义:

 HttpPostedFile hpf = hfc[i];

然后你问:

 if (hpf == (".jpg") || fileExt == (".gif") || fileExt == (".bmp") || fileExt == (".png") || fileExt == (".jpeg"))

但是 hpf 是HttpPostedFile而不是string

将您的代码更改为:

 if (fileExt == (".jpg") || fileExt == (".gif") || fileExt == (".bmp") || fileExt == (".png") || fileExt == (".jpeg"))

此外,您还有一个用于所有上传文件的循环。

在该循环开始之前,您将获得文件扩展名然后执行循环:

for (int i = 0; i < hfc.Count; i++)

您需要检查循环内的文件扩展名:

for (int i = 0; i < hfc.Count; i++)
         string fileExt = Path.GetExtension(hpf.FileName); //Get The File

否则,如果您的第一个文件具有允许的文件扩展名,则上传中的所有文件都将被保存。

如果文件名中.有一个文件名,.例如FileName.Something.jgp. 而是使用Path.GetFileNameWithoutExtension

如果在同一秒上传了多个同名文件,您为文件赋予唯一名称的时间戳也会导致问题。我总是看到这个问题。您可能想要包括毫秒。

如果你想跳过无效文件使用continue而不是break

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


    for (int i = 0; i < hfc.Count; i++)
    {
        HttpPostedFile hpf = hfc[i];

        if (hpf.ContentLength > 0)
        {
            ///full path name to check exist or not
            fullname = string.Format("{0}\\{1}", PicDir, Path.GetFileName(hpf.FileName.Replace(" ", "_")));
            // get the file name here.
            string fileExt = Path.GetExtension(FileUpload1.FileName); //Get The File Extension 

            if (FileExt == (".jpg") || fileExt == (".gif") || fileExt == (".bmp") || fileExt == (".png") || fileExt == (".jpeg"))
            {
                if (hpf.ContentLength.Length > 200000)
                {

                    ClientScript.RegisterStartupScript(Type.GetType("System.String"), "messagebox", "<script type=\"text/javascript\">alert('File Tidak boleh lebih dari 200 kb');</script>");
                    continue; // break will exit the loop, use continue to go to the next file
                }


                if (File.Exists(fullname))
                {

                    string f = Path.GetFileNameWithoutExtension(hpf.FileName.Replace(" ", "_"));
                    string timeStamp = DateTime.Now.ToString("yymdHm"); // this could fail, be more specific with your timestamp;
                    filename = f + timeStamp + fileExt;
                    // this will not work correctly if more than one "." in the file name
                    //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); //save as
                InsertHazardDoc(id_hazard_report, filename);
            }
            else
            {
                FileUpload1.Focus();
                ClientScript.RegisterStartupScript(Type.GetType("System.String"), "messagebox", "<script type=\"text/javascript\">alert('File Bukan Format Gambar');</script>");
                continue;// break will exit the loop, use continue to go to the next file
            }
        }
        //}

    }
}

我看你是新来的。花点时间阅读这个stackoverflow.com/help/someone-answers

如果我首先上传 file.pdf 和第二个 file.jpg 。这是我的代码不跳过 file.jpg 插入数据库。但如果我首先上传 file.jpg 和第二个 file.pdf 完成。可以帮我?

break is causing you to exit the loop. I updated and added more comments of other issues

ok done. one question again . why file size function 200 kb not function? if (FileUpload1.FileBytes.Length > 200000) or if(hpf.ContentLength > 200000)// 200 kb

Get rid of FileUpload1. You need to check hpf which is the current file in the loop. See update

微信小程序

微信扫一扫体验

微信公众账号

微信扫一扫加关注

发表
评论
返回
顶部