我如何重新检查上传中的图像

时间:2017-07-11 05:38:41

标签: javascript c# asp.net file upload

//为什么这个代码没有功能,如果我上传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跟随插入到数据库

1 个答案:

答案 0 :(得分:0)

在此定义:

 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
            }
        }
        //}

    }
}