Is there a way to verify that only the image was uploaded?

// why isn't this code working when I upload 1.chicken.jpg with a size of 180kb and 2.chicken.pdf, but only the chicken.pdf file gets inserted into the database?

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

        }

// why this code no function if me upload 1.chicken.jpg 180kb 2.chicken.pdf but chicken.pdf follow insert to database

Answer №1

Outlined here is the process for:

 HttpPostedFile hpf = hfc[i];

Subsequently, there is an inquiry:

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

It should be noted that hpf is a HttpPostedFile, not a string.

To rectify this, adjust your code to:

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

In addition, there is a loop for all uploaded files.

Prior to commencing the loop, you're retrieving the file extension and then executing the loop:

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

The file extension check needs to be within the loop:

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

If the first file has an allowed file extension, all files in the upload will consequently be saved.

Your method of splitting the file name based on . may cause issues if there is a . in the file name such as FileName.Something.jgp. Utilize Path.GetFileNameWithoutExtension instead.

Furthermore, the timestamp used to provide a unique name for the file can lead to problems if multiple files with identical names are uploaded at the same second. Consider including milliseconds.

To skip invalid files, use continue instead of break:

 
// Insert updated code snippet here

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Guide on adjusting the CSS styling of elements in real-time from the backend using a user customization panel to modify the appearance of various web pages

Imagine a scenario where we have a website consisting of multiple pages, including a user account page. The user has the ability to modify the color, font size, and style of certain elements on other pages for their own viewing preferences. How can this fu ...

Impact when returning a React.FC Component

Using React, I have encountered a challenge with my site: I have a function that generates a Card component displaying information about my store's products (#1). To display this on the screen, I map through the array returned by the backend and pass ...

Place the array contents inside a fresh division labeled "row" once it reaches 4 elements

I'm currently working with Bootstrap and I want to display my output in a specific grid format. I have successfully grouped my array into piles of 3 and placed them in a div with the classname "row". However, I'm facing an issue where the element ...

A collection of strings where each item is unique

I have a binding list to a repeater in ASP.NET. Currently, it is displaying like this: https://i.sstatic.net/6CgUE.png But I want it to display like this: https://i.sstatic.net/3eUI3.png Here's my code: <asp:Repeater ID="RptID" runat="server" ...

Interested in utilizing my current asp.net website on a desktop

I have recently started exploring asp.net and have learned everything so far from the web. I successfully built a website that is functioning well, but now I need to convert it into a desktop application for various reasons. I want both versions to be fu ...

Converting a nested JSON object into a specific structure using TypeScript

In the process of developing a React app with TypeScript, I encountered a challenging task involving formatting a complex nested JSON object into a specific structure. const data = { "aaa": { "aa": { "xxx&qu ...

Combining Date and Time in Javascript: A Guide

As a JavaScript beginner, I am struggling with combining date and time pickers. Despite finding similar questions, I have not yet found the solution I need. I have two inputs: one for the datePicker and another for the timePicker. <form> <div clas ...

Tips on detecting array changes in a computed property originating from Vuex

I am currently working with an array of computed properties that are generated from the store's state: computed: { ...mapGetters([ '$tg', ]), ...mapState({ podcastList: state => state.listening.podcastList, }), tabList: ...

Is there a way to retrieve a file from an HTTP server and store it as a byte array in

Currently, I am attempting to retrieve a file from a web address and convert it into a byte array. I have successfully used File.ReadAllBytes when dealing with local files, but have not found a straightforward method to achieve this for web-based files. I ...

Issue with saving images from Ionic App on WCF Service

Having an issue with saving images correctly in my WCF Service when uploading through Ionic application. The image is being saved as invalid. [OperationContract] [WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBod ...

Angular 12: How to detect when a browser tab is closing and implement a confirmation dialog with MatDialog

I have a scenario where I am checking if the browser tab is closed using the code below. It currently works with windows dialog, but I would like to incorporate MatDialog for confirmation instead. @HostListener('window:beforeunload', ['$eve ...

Error TS2307: Module 'angular' could not be located

I have encountered an error in my project and despite searching for solutions, I haven't been able to find one that addresses my specific issue. It seems like a simple problem, but I can't figure out what I'm missing. The error arises in th ...

Saving compiled babel files to the corresponding directory level

Is there a way to output compiled babel files in the same directory as the source files? Currently, my script generates the compiled files in a separate folder while maintaining the folder structure. This is achieved through the following code snippet in m ...

Unable to show the name of the chosen file

After customizing the input [type = file], I successfully transformed it into a button with a vibrant green background. Here is the code snippet that enabled this transformation: <style> #file { height:0px; opacity:0; } ...

Issue with vuejs build process not incorporating relative paths into the final output

I'm encountering a problem trying to run my Vue.js app from the dist folder. After searching on this site, I came across a helpful thread titled Vuejs, Difficulties to build with relative path, which suggested the following solution: Create a "vu ...

Once the stripe token is generated, proceed to submit the form

Having issues submitting a form using jQuery with the Stripe.js plugin. I need to submit the form after creating a Stripe token. The jQuery validation is working correctly, but I'm getting an error message in the console saying "object is not a functi ...

Modify the specified pattern with regex only if it does not appear in a particular location in the content

Our tool development heavily relies on regex for various functionalities. One key aspect involves replacing placeholders with actual values dynamically using standard JavaScript's `RegExp`. All placeholder formats are similar to this: {{key}} In mo ...

Ways to insert data in angularjs

As I attempt to add data to a list using the addGroup function, I encounter a type-error. The error message reads: "TypeError: Cannot read property 'push' of undefined" at r.$scope.addGroup (main.js:7) at fn (eval at compile (angular ...

Exiting the Protractor timeout setting for Safari WebDriver

While I have experience with unit tests using Karma, my office is now interested in integration tests, specifically to test cross-browser capabilities. Protractor seemed like the best option for this, so I began working on some basic dashboard tests. Howev ...

Insert a div element into the JavaScript file

I have a JavaScript code snippet that needs to be inserted after the "Artwork" section. Here is the code: <div class="image-upload"> <label for="files"> <img src="ohtupload.jpg"> </label> </di ...