locked
Compress files before uploading RRS feed

  • Question

  • User-1753299103 posted

    I have for years asking my site visitors to compress their word, pdf and/or image files to a certain size before uploading. It has in occasions discouraged our visitors to proceed with the final registration process.

    I am using razor syntax and I was wondering if their is better way to have the files automatically compressed and then uploaded.  I am hosting my web app on azure platform, if that is of any significance.

    Regards

    Sunday, July 28, 2019 12:17 AM

Answers

All replies

  • User-821857111 posted

    There appear to be some JavaScript libraries that can compress images prior to upload (https://stackoverflow.com/questions/5607396/compress-images-on-client-side-before-uploading). Maybe a search will reveal others that cater for PDF etc. But you can't do this with C# on the client using Web Pages/Razor Pages.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, July 29, 2019 7:00 AM
  • User-719153870 posted

    Hi engcanada,

    You can use filestream to compress files to .zip.

    Please refer to below code:

    protected void Button1_Click(object sender, EventArgs e)
            {
                string f_name = @"./Upload2/Asp.Net MVC.docx";//add your own filename automatically
                fileCompress(f_name);
            }
    
            public static void fileCompress(string f_name)
            {
                string filename = HttpContext.Current.Server.MapPath(f_name);
                FileStream infile = File.OpenRead(filename);
                byte[] buffer = new byte[infile.Length];
                infile.Read(buffer, 0, buffer.Length);
                infile.Close();
    
                FileStream outfile = File.Create(Path.ChangeExtension(filename, "zip"));
                GZipStream gz = new GZipStream(outfile, CompressionMode.Compress);
                gz.Write(buffer, 0, buffer.Length);
                gz.Close();
            }

    Here's the result of this demo:

    Best Regard,

    Yang Shen

    Monday, July 29, 2019 9:12 AM
  • User-821857111 posted

    You can use filestream to compress files to .zip.
    How does that compress the file BEFORE upload?

    Monday, July 29, 2019 10:52 AM