简体   繁体   中英

How to Check that image already exists/attached while Uploading multiple images at a time in c#, asp.net

I am going to upload multiple images using asp.net file upload control. there are many suggestions in mind for this solution.. currently am using DataTable . all images put in DataTable view state and then while checking its rows.. I mark a Check on FileName if already exists then it will not Upload.. But if any user browse/upload an image having same name but from different Folder/Path it will become an issue. my code is here

 private void AttachImage()
        {
                string fileName = Convert.ToString(Guid.NewGuid());
                string filePath = "images/" + fileName;
                fileName = Path.GetFileName(ImageUpload.PostedFile.FileName);
                ImageUpload.SaveAs(Server.MapPath(filePath));
                DataTable dt = new DataTable();

                DataColumn dc = new DataColumn();
                dc = new DataColumn("Name", typeof(String));
                dt.Columns.Add(dc);

                dc = new DataColumn("Path", typeof(String));
                dt.Columns.Add(dc);

                dt.Rows.Add(fileName, filePath);
                if (ViewState["dt"] == null)
                {
                    ViewState["dt"] = dt;
                }
                else// (ViewState["dt"] != null)
                {
                    DataTable tmpTable = (DataTable)ViewState["dt"];
                    tmpTable.Rows.Add(fileName, filePath);
                    ViewState["dt"] = tmpTable;
                }


            lstProductsImage.DataSource = (DataTable)ViewState["dt"];
            lstProductsImage.DataBind();

        }

Secondly: using GUID , to assign images. but it will also not suitable as it will only change the FileName and we are not able to determine whether this file exist on the server or not. Third Option can be that if the file already exists in the upload folder we ask the user if he/she wants to overwrite the existing file. Or I should use System.IO.File.Exists(pathToCheck)) ??

I want Good Suggestions from your side ... Thanks: Saquib

Dude! I review your code and from my point of view... 1- Dont Use GUID in this senario. 2- Get File Name using Following code (Change it as per your requirement)

string fileName = System.IO.Path.GetFileName(dsPhotosFiles.Tables[0].Rows[i]["filePath"].ToString());

3- Get Image Bytes using array (for example byte[] imageBytes;)

byte[] imageBytes;
  imageBytes = (byte[])dsPhotosFiles.Tables[0].Rows[i]["fileBytes"];

OR Read file into a data stream AND && Put a Check on FileName + FilePath using((System.IO.File.Exists(Server.MapPath(SavePath + Filename))) ) + ImageBytes

byte[] myData = new Byte[nFileLen];

4- After that Check whether the file is really a JPEG by opening it (can get some help from following code..

System.Drawing.Image.GetThumbnailImageAbort myCallBack = 
                       new System.Drawing.Image.GetThumbnailImageAbort(ThumbnailCallback);
        Bitmap myBitmap;

       try
        {
            myBitmap = new Bitmap(Server.MapPath(sSavePath + sFilename));

            // If jpg file is a jpeg, create a thumbnail filename that is unique.
            file_append = 0;
            string sThumbFile = System.IO.Path.GetFileNameWithoutExtension(myFile.FileName)
                                                     + sThumbExtension + ".jpg";
            while (System.IO.File.Exists(Server.MapPath(sSavePath + sThumbFile)))
            {
                file_append++;
                sThumbFile = System.IO.Path.GetFileNameWithoutExtension(myFile.FileName) + 
                               file_append.ToString() + sThumbExtension + ".jpg";
            }

            // Save thumbnail and output it onto the webpage
            System.Drawing.Image myThumbnail
                    = myBitmap.GetThumbnailImage(intThumbWidth, 
                                                 intThumbHeight, myCallBack, IntPtr.Zero);
            myThumbnail.Save (Server.MapPath(sSavePath + sThumbFile));
            imgPicture.ImageUrl = sSavePath + sThumbFile;

            // Displaying success information
            lblOutput.Text = "File uploaded successfully!";

            // Destroy objects
            myThumbnail.Dispose();
            myBitmap.Dispose();
        }
        catch (ArgumentException errArgument)
        {
            // The file wasn't a valid jpg file
            lblOutput.Text = "The file wasn't a valid jpg file.";
            System.IO.File.Delete(Server.MapPath(sSavePath + sFilename));
        }

Hope This will be Helpful to You... Regards: Azeem Raavi

If you are not allowing duplicates (and there is a check in place), why would you rename the files? Just save them under their original name and use the File.Exists check when subsaquent uploads are performed.

Also, you concern about the folder/path wouldn't be an issue because all files are uploaded to the images folder based on your code.

let you try in Java script,may be that's help you know

in my aspx flie in java code

$("#UPLOAD_BUTTON").uploadify({
                  'buttonClass'   : "ui-icon ui-icon-plus",
                  'swf'            : '/web/uploader/uploadify.swf',                  
                  'uploader'       : '/web/uploader/Uploadify.ashx?ASPSESSID=<% =Session.SessionID %>',
                  'cancelImage'    : '/web/uploader/uploadify-cancel.png',
                  'folder'         : '/uploads',
                  'multi'          : true,
                  'auto'           : true,
                  'checkExisting'  : '/web/uploader/Uploadify.ashx?check=true',
                  'queueID'        : "UploadFilesQueue",
                  'buttonText'     : ' ',          
                  'hideButton'     : true,  
                  'fileTypeExts'   : '*.*',
                  'fileTypeDesc'   : 'Alle Dateien',
                  'onQueueComplete': function(event,data) {                      
                  },
                  postData : {
                    "stepID" : $("#lblStepID").text(),
                    "ASPSESSID" : "<% =Session.SessionID %>",                    
                  }
              });

you need to pass the SessionID as a parameter and grab it in the Global.asax File or you will create a new ASP.NET session on every Upload.

In the jquery.uploadify.js File you need to find this function and modify it

function onUploadStart(file) 

here you can react on the Returncode from you Upload-ASHX file.

I use different return codes for different conditions like

ReturnCode=1 -> File allready Exists
ReturnCode=2 -> File is to Big

....

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM