locked
upload image type validation and resize be fore upload RRS feed

  • Question

  • kindly advise what changes required :-

    1.) only upload . jpeg. jpg, gif, png .pdf   file tye.

    2.) reduce file size during upload. 

    below code is working fine but without above two point 

    if (FileImgesave1.PostedFile != null)
            {
                string imgfile = Path.GetFileName(FileImgesave1.PostedFile.FileName);
    
                FileImgesave1.SaveAs(path + txtReportNo.Value + "_" + "Report" + "_" + imgfile);
    
                string Report = (@"Images/Misc/Service_Reports/" + txtReportNo.Value + "_" + "Report" +"_"+ imgfile);
    
    
                SqlConnection connn = new SqlConnection(ConfigurationManager.ConnectionStrings["connection "].ConnectionString);
    
                connn.Open();
                           
                
               
               
    
                
                com.ExecuteNonQuery();
    
                Response.Redirect(Request.Url.AbsoluteUri);
               
    
                connn.Close();
                
    
            }
    
            else
    
            {
                lblerer.Text = "Please Select  File First";
    
            }
    

    Wednesday, August 19, 2020 6:38 AM

Answers

  • Try this preliminary function:

    static bool IsFileGood( string path )
    {
    	try
    	{
    		using( Image image = Image.FromFile( path ) )
    		{
    			return
    				image.RawFormat.Equals( ImageFormat.Jpeg ) ||
    				image.RawFormat.Equals( ImageFormat.Png ) ||
    				image.RawFormat.Equals( ImageFormat.Gif );
    		}
    	}
    	catch
    	{
    		// TODO: analyse the exception 
    	}
    
    	try
    	{
    		using( FileStream fs = File.OpenRead( path ) )
    		{
    			byte[] a = new byte[4];
    			fs.Read( a, 0, a.Length );
    			string s = Encoding.ASCII.GetString( a );
    
    			return s == "%PDF";
    		}
    	}
    	catch
    	{
    		// TODO: analyse the exception 
    	}
    
    	return false;
    }

    Call it before processing the file:

    if (FileImgesave1.PostedFile != null)

    {

       if( ! IsFileGood(FileImgesave1.PostedFile.FileName))

       {

          lblerer.Text = "Please select a good file.";

       }

       else

       {

          process the file…

      

    (Also add a reference to System.Drawing).

    For the second problem, do you want to compress the file? Usually such files are already compressed.




    • Edited by Viorel_MVP Wednesday, August 19, 2020 8:26 AM
    • Marked as answer by saqsaqPK Tuesday, August 25, 2020 6:13 AM
    Wednesday, August 19, 2020 8:19 AM
  • thanks for your reply Copy function  

    but error show form.file.(path)

    can you provide more detail about From.File(Path)

    tatic bool IsFileGood(string path)
    {
        try
        {
            using (Image image = Image.FromFile(path))
            {
                return
                    image.RawFormat.Equals(ImageFormat.Jpeg) ||
                    image.RawFormat.Equals(ImageFormat.Png) ||
                    image.RawFormat.Equals(ImageFormat.Gif);
            }


    Show the error. If it is a compilation error, then add the suggested reference to System.Drawing assembly, and also add the ‘using System.Drawing;’ directive to the beginning of code file.



    • Edited by Viorel_MVP Friday, August 21, 2020 7:48 AM
    • Marked as answer by saqsaqPK Tuesday, August 25, 2020 6:14 AM
    Friday, August 21, 2020 7:48 AM
  • Hi

    get the extention from file 

    var  InputFileext = System.IO.Path.GetExtension(FileImgesave1.PostedFile.FileName);  

    use as per your requirement

    Thanks and regards

    • Marked as answer by saqsaqPK Tuesday, August 25, 2020 6:15 AM
    Friday, August 21, 2020 9:23 AM

All replies

  • Try this preliminary function:

    static bool IsFileGood( string path )
    {
    	try
    	{
    		using( Image image = Image.FromFile( path ) )
    		{
    			return
    				image.RawFormat.Equals( ImageFormat.Jpeg ) ||
    				image.RawFormat.Equals( ImageFormat.Png ) ||
    				image.RawFormat.Equals( ImageFormat.Gif );
    		}
    	}
    	catch
    	{
    		// TODO: analyse the exception 
    	}
    
    	try
    	{
    		using( FileStream fs = File.OpenRead( path ) )
    		{
    			byte[] a = new byte[4];
    			fs.Read( a, 0, a.Length );
    			string s = Encoding.ASCII.GetString( a );
    
    			return s == "%PDF";
    		}
    	}
    	catch
    	{
    		// TODO: analyse the exception 
    	}
    
    	return false;
    }

    Call it before processing the file:

    if (FileImgesave1.PostedFile != null)

    {

       if( ! IsFileGood(FileImgesave1.PostedFile.FileName))

       {

          lblerer.Text = "Please select a good file.";

       }

       else

       {

          process the file…

      

    (Also add a reference to System.Drawing).

    For the second problem, do you want to compress the file? Usually such files are already compressed.




    • Edited by Viorel_MVP Wednesday, August 19, 2020 8:26 AM
    • Marked as answer by saqsaqPK Tuesday, August 25, 2020 6:13 AM
    Wednesday, August 19, 2020 8:19 AM
  • Hi saqsaqPK,

    Thank you for posting here.

    You can use the following code to reduce the size of the picture, which is achieved by losing a certain quality.

            static void Main(string[] args)
            {
                Image myImage = Image.FromFile(@"D:\test\pictures\1.jpg", true);
                // Save the image with a quality of 50% 
                SaveJpeg(@"D:\test\pictures\2.jpg", myImage, 50);
            }
            public static void SaveJpeg(string path, Image img, int quality)
            {
                if (quality < 0 || quality > 100)
                    throw new ArgumentOutOfRangeException("quality must be between 0 and 100.");
    
                // Encoder parameter for image quality 
                EncoderParameter qualityParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, quality);
                // JPEG image codec 
                ImageCodecInfo jpegCodec = GetEncoderInfo("image/jpeg");
                EncoderParameters encoderParams = new EncoderParameters(1);
                encoderParams.Param[0] = qualityParam;
                img.Save(path, jpegCodec, encoderParams);
            }
    
            /// <summary> 
            /// Returns the image codec with the given mime type 
            /// </summary> 
            private static ImageCodecInfo GetEncoderInfo(string mimeType)
            {
                // Get image codecs for all image formats 
                ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
    
                // Find the correct image codec 
                for (int i = 0; i < codecs.Length; i++)
                    if (codecs[i].MimeType == mimeType)
                        return codecs[i];
    
                return null;
            }

    Best Regards,

    Timon


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    Wednesday, August 19, 2020 9:08 AM
  • This is a web app so "blocking" certain file types would be handled on the UI side. For the UI side it depends on what UI framework you're using but ultimately it involves limiting the available types in the file browser.

    On the server side you should still enforce that certain files were uploaded by checking as well (because the UI can lie). However there are tradeoffs to doing this that you need to be aware of.

    1) Checking the file extension is the fastest and safest route but only prevents a user from accidentally selecting the wrong file as they can easily rename an exe to an image.

    2) You can load the file into memory to verify it is valid but this is slow compared to other approaches. It is more accurate but might be overkill.

    3) There is the issue of file persistence as well. If the file is very large then keeping it in a byte array is going to eat up memory but the alternative is to save to disk. If you save to disk then you need to clean up the file. Viruses become a concern here. If the file is open then it is possible to have a virus/malware run. Your server better have AV running but that generally only works against files on the file system so if you are worried about viruses then you'll need to save to disk to trigger AV anyway.

    4) A happy medium between just checking the file extension and loading the entire file would be opening the file as a stream and reading a few bytes of the header. The file types you mentioned have well defined headers that you can quickly verify exist. This would be very fast and give you the semblance that the user uploaded the correct file but it isn't foolproof. Still it is fast enough for servers that may have 100s or 1000s of requests running at the same time.

    Ultimately it will boil down to what you're trying to prevent: a user accidentally uploading the wrong file type (client UI validation), a user uploading a wrong file type on purpose (client and server validation) or preventing upload of malicious stuff (client, server and AV validation).



    Michael Taylor http://www.michaeltaylorp3.net

    Wednesday, August 19, 2020 2:34 PM
  • thanks for your reply Copy function  

    but error show form.file.(path)

    can you provide more detail about From.File(Path)

    tatic bool IsFileGood(string path)
    {
        try
        {
            using (Image image = Image.FromFile(path))
            {
                return
                    image.RawFormat.Equals(ImageFormat.Jpeg) ||
                    image.RawFormat.Equals(ImageFormat.Png) ||
                    image.RawFormat.Equals(ImageFormat.Gif);
            }

    Friday, August 21, 2020 5:10 AM
  • thanks for your reply Copy function  

    but error show form.file.(path)

    can you provide more detail about From.File(Path)

    tatic bool IsFileGood(string path)
    {
        try
        {
            using (Image image = Image.FromFile(path))
            {
                return
                    image.RawFormat.Equals(ImageFormat.Jpeg) ||
                    image.RawFormat.Equals(ImageFormat.Png) ||
                    image.RawFormat.Equals(ImageFormat.Gif);
            }


    Show the error. If it is a compilation error, then add the suggested reference to System.Drawing assembly, and also add the ‘using System.Drawing;’ directive to the beginning of code file.



    • Edited by Viorel_MVP Friday, August 21, 2020 7:48 AM
    • Marked as answer by saqsaqPK Tuesday, August 25, 2020 6:14 AM
    Friday, August 21, 2020 7:48 AM
  • Hi

    get the extention from file 

    var  InputFileext = System.IO.Path.GetExtension(FileImgesave1.PostedFile.FileName);  

    use as per your requirement

    Thanks and regards

    • Marked as answer by saqsaqPK Tuesday, August 25, 2020 6:15 AM
    Friday, August 21, 2020 9:23 AM
  • Thank you so much for  guide line , Problem solved 
    Tuesday, August 25, 2020 6:14 AM