Upload Any File and Show the Thumbnail of Uploaded File in MVC

Concept

This project converts txt, doc, docx, xls, xlsx, ppt, pptx and rtf extension files into a PDF and then converts the created PDF into a JPEG format. When a user uploads the file and clicks on the Submit button then first page of the uploaded file is converted into the image file and shown on the browser without a postback. For converting from a doc, docx, xls, xlsx, ppt, pptx or rtf file, Microsoft Office 2007 or later should be installed in your system. The uploaded file and the converted PDF file will be stored in the Attachments Folder and the converted JPEG file will be stored in the Preview Folder of this project.

1. First of all open Visual Studio 2010 or later and then select "File" -> "New" -> "Project..." and click on ASP.NET MVC3 Web Application in Visual C#, name the project FileUploader. Then add the following folders to your project.

  1. Classes
  2. UploadBooks

    Attachments (Inside the UploadBooks folder)
    Preview (Inside the Attachments folder)

2. Create a controller named HomeController and in this controller create an ActionResult method named FileUploader.

  1. namespace FileUploader.Controllers  
  2. public class HomeController : Controller  
  3. {  
  4.     // GET: /Home/  
  5.     public ActionResult FileUploader()  
  6.     {  
  7.         return View();  
  8.     }  
  9. } 

3. Now create a view, right-click on the Fileuploader() and select Add View and then click OK.

Write the following code in this view.

  1. @{<br /> ViewBag.Title = "FileUploader";  
  2.          Layout = "~/Views/Shared/_Layout.cshtml";  
  3. }  
  4. <h2>  
  5.     FileUploader</h2>  
  6. @using (Html.BeginForm())  
  7. {  
  8.     <div>  
  9.         <img src="" width="100" height="100" id="msg" />  
  10.     </div>  
  11.     <div>  
  12.         <p id="message">  
  13.         </p>  
  14.     </div>  
  15.     <input type="file" name="file" id="file" />  
  16.     <input type="button" class="clickClass" value="submit" id="submit" />  
  17. } 

4. Create a model named FileUploaderModel.cs and add the following code to this. Also add the class file “PdfConvert.cs” to the Classes folder, add the “gsdll32.dll”, in other words Ghost Script, in the bin folder of your project and the reference file TextPdf.dll. This code converts the PDF file into single a JPEG file. Download the required files from the link in the last.

  1. namespace FileUploader.Models  
  2. {  
  3.     public class FileUploaderModel  
  4.     {  
  5.         //public string guid { get; set; }  
  6.         PdfToImage.PDFConvert PdfConverter = new PdfToImage.PDFConvert();  
  7.         //Convert the pdf into Single Image.  
  8.         public void ConvertSingleImage(string filename)  
  9.         {  
  10.              try  
  11.              {  
  12.                  PdfConverter.RenderingThreads = 5;  
  13.                  PdfConverter.TextAlphaBit = 4;  
  14.                  PdfConverter.OutputToMultipleFile = false;  
  15.                  PdfConverter.FirstPageToConvert = -1;  
  16.                  PdfConverter.LastPageToConvert = -1;  
  17.                  PdfConverter.FitPage = false;  
  18.                  PdfConverter.JPEGQuality = 10;  
  19.                  PdfConverter.OutputFormat = "jpeg";  
  20.                  System.IO.FileInfo input = new FileInfo(filename);  
  21.                  string[] str = input.Name.Split('.');  
  22.                  string output = string.Format("{0}\\{1}{2}", input.Directory + "\\Preview", str[0].ToString(), ".jpg");  
  23.                  while (System.IO.File.Exists(output))  
  24.                  {  
  25.                      File.Delete(output);  
  26.                      output = string.Format("{0}\\{1}{2}", input.Directory + "\\Preview", str[0].ToString(), ".jpg");  
  27.                  }  
  28.             }  
  29.         }  
  30.         catch (Exception ex)  
  31.         {  
  32.         }  
  33.         return;  
  34.     }  
  35. } 

Converting the text file into JPEG file

1. Add the following code to your controller to convert the text file that will come from the FileUploader view into a PDF and then into the JPEG format and finally pass the converted JPEG file path back to the FileUploader view.

Converting the text file into JPEG file

2. Add the following code to your controller to convert the text file that will come from the FileUploader view into the PDF and then into the JPEG format and finally pass the converted JPEG file path back to the FileUploader view.

  1. [HttpPost]  
  2. public ActionResult FileUploader(FileUploaderModel upload)  
  3. {  
  4.     string guid = Guid.NewGuid().ToString();  
  5.     //upload.guid = guid;  
  6.     string msg = "Something went wrong, Your file was not uploaded.";  
  7.     HttpPostedFileBase file = Request.Files[0];  
  8.     string FinalPath = "";  
  9.     if (file != null && file.ContentLength > 0)  
  10.     {  
  11.         var fileName = Path.GetFileName(file.FileName); // extract only the fielname  
  12.         var ext = Path.GetExtension(fileName.ToLower()); //extract only the extension of filename and then convert it into lower case.  
  13.         //var fileNameWithoutExt = Path.GetFileNameWithoutExtension(fileName);  
  14.         var path = Server.MapPath("~/UploadBooks/Attachments/" + guid + ext);  
  15.         file.SaveAs(path);  
  16.         if (ext == ".txt"//If the file is a "text" file.  
  17.         {  
  18.            string filePath = "";  
  19.            string filePath12 = "";  
  20.            filePath = Server.MapPath("~/UploadBooks/Attachments/" + guid + ext);  
  21.            filePath12 = Server.MapPath("~/UploadBooks/Attachments/");  
  22.            FinalPath = Server.MapPath("~/UploadBooks/Attachments/" + guid + ".pdf");  
  23.            TextPDF.PdfWriter pdfWriter = new TextPDF.PdfWriter(842.0f, 1190.0f, 10.0f, 10.0f);  
  24.            pdfWriter.Getfilename(guid, filePath12); //Convert the "txt" file into "pdf" file  
  25.            if (filePath.Length > 0)  
  26.            pdfWriter.Write(filePath); //Store the converted pdf file into Attachments folder  
  27.            upload.ConvertSingleImage(FinalPath); //Convert the pdf file into "jpg" file, the code is written in FileUploaderModel.cs  
  28.            string str = "../../UploadBooks/Attachments/Preview/" + guid + ".jpg"  
  29.            return Content(str);  
  30.         }  
  31.     }  
  32. } 

3. Now add the following JavaScript to your view that will pass the file information to your controller and then return the path of the image that will be built from your controller HTTPPOST FileUploader method.

  1. <script type="text/javascript">  
  2.     document.getElementById('submit').onclick = function () {  
  3.         var formdata = new FormData(); //FormData object  
  4.         var fileInput = document.getElementById('file');  
  5.         //Iterating through each files selected in fileInput  
  6.         for (i = 0; i < fileInput.files.length; i++) {  
  7.             //Appending each file to FormData object  
  8.             formdata.append(fileInput.files[i].name, fileInput.files[i]);  
  9.         }  
  10.         //Creating an XMLHttpRequest and sending  
  11.         var xhr = new XMLHttpRequest();  
  12.         xhr.open('POST''/Home/FileUploader');  
  13.         xhr.send(formdata);  
  14.         xhr.onreadystatechange = function () {  
  15.             if (xhr.readyState == 4 && xhr.status == 200) {  
  16.                 var msg = "Your file was successfully uploaded";  
  17.                 $("#msg").attr('src', xhr.responseText);  
  18.                 $("#message").text(msg)  
  19.             }  
  20.         }  
  21.         return false;  
  22.     }  
  23. </script> 

Converting the xls or xlsx file into a JPEG file

1. Add the following method code to your model to convert the xls or xlsx file into a PDF file and also add the reference file Microsoft.Office.Interop.Excel.dll.

  1. //Method to convert the Excel file into Pdf  
  2. public bool ExportWorkbookToPdf(string workbookPath, string outputPath)  
  3. {  
  4.     // If either required string is null or empty, stop and bail out  
  5.     if (string.IsNullOrEmpty(workbookPath) || string.IsNullOrEmpty(outputPath))  
  6.     {  
  7.         return false;  
  8.      }  
  9.      // Create COM Objects  
  10.      Microsoft.Office.Interop.Excel.Application excelApplication;  
  11.      Microsoft.Office.Interop.Excel.Workbook excelWorkbook;  
  12.      excelApplication = new Microsoft.Office.Interop.Excel.Application();   
  13.      // Create new instance of Excel  
  14.      excelApplication.ScreenUpdating = false// Make the process invisible to the user  
  15.      excelApplication.DisplayAlerts = false// Make the process silent  
  16.      excelWorkbook = excelApplication.Workbooks.Open(workbookPath); // Open the workbook that you wish to export to PDF  
  17.      // If the workbook failed to open, stop, clean up, and bail out  
  18.      if (excelWorkbook == null)  
  19.      {  
  20.          excelApplication.Quit();  
  21.          excelApplication = null;  
  22.          excelWorkbook = null;  
  23.          return false;  
  24.      }  
  25.      var exportSuccessful = true;  
  26.      try  
  27.      {  
  28.          // Call Excel's native export function (valid in Office 2007 and Office 2010, AFAIK)  
  29.          excelWorkbook.ExportAsFixedFormat(Microsoft.Office.Interop.Excel.XlFixedFormatType.xlTypePDF, outputPath);  
  30.      }  
  31.      catch (System.Exception ex)  
  32.      {  
  33.          // Mark the export as failed for the return value...  
  34.          exportSuccessful = false;  
  35.          // Do something with any exceptions here, if you wish...  
  36.          // MessageBox.Show...  
  37.      }  
  38.      finally  
  39.      {  
  40.           // Close the workbook, quit the Excel, and clean up regardless of the results...  
  41.           excelWorkbook.Close();  
  42.           excelApplication.Quit();  
  43.           excelApplication = null;  
  44.           excelWorkbook = null;  
  45.       }  
  46.       return exportSuccessful;  
  47. } 

2. Add the following code to your controller to convert the xls or xlsx file that will come from the FileUploader view into the PDF and then into JPEG format and finally pass the converted JPEG file back to the FileUploader view.

  1. //If the file is a "Excel" file.  
  2. else if (ext == ".xls" || ext == ".xlsx")  
  3. {  
  4.     string inputFilePath = ""string outputFilePath = "";  
  5.     inputFilePath = Server.MapPath("~/UploadBooks/Attachments/" + guid +ext);  
  6.     outputFilePath = Server.MapPath("~/UploadBooks/Attachments/" + guid + ".pdf");  
  7.     FinalPath = Server.MapPath("~/UploadBooks/Attachments/" + guid + ".pdf");  
  8.     upload.ExportWorkbookToPdf(inputFilePath, outputFilePath); //Convert the Excel file into "pdf" file  
  9.     upload.ConvertSingleImage(FinalPath); //Convert the pdf file into "jpg" file, the code is written in FileUploaderModel.cs  
  10.     string str = "../../UploadBooks/Attachments/Preview/" + guid + ".jpg";  
  11.     return Content(str);  
  12. } 

3. Add the following method code to your model to convert the doc, docx or RTF file into a PDF file and also add the reference file Microsoft.Office.Interop.Word.dll .

  1. //Method to convert the Word file into Pdf  
  2. public Microsoft.Office.Interop.Word.Document wordDocument { getset; }  
  3. public bool ExportWordFileToPdf(string workbookPath, string outputPath)  
  4. {  
  5.     Microsoft.Office.Interop.Word.Application appWord = new Microsoft.Office.Interop.Word.Application();  
  6.     wordDocument = appWord.Documents.Open(workbookPath);  
  7.     var exportSuccessful = true;  
  8.     try  
  9.     {  
  10.         wordDocument.ExportAsFixedFormat(outputPath, WdExportFormat.wdExportFormatPDF);  
  11.     }  
  12.     catch (System.Exception ex)  
  13.     {  
  14.          // Mark the export as failed for the return value...  
  15.          exportSuccessful = false;  
  16.         // Do something with any exceptions here, if you wish...  
  17.         // MessageBox.Show...  
  18.     }  
  19.     finally  
  20.     {  
  21.          // Close the wordDocument, quit the Document, and clean up regardless of the results...  
  22.          ((_Document)wordDocument).Close();  
  23.          ((_Application)appWord).Quit();  
  24.          appWord = null;  
  25.          wordDocument = null;  
  26.     }  
  27.     return exportSuccessful;  
  28. } 

4. Add the following code to your controller to convert the doc, docx or RTF file that will come from the FileUploader view into a PDF and then into JPEG format and finally pass the converted JPEG file back to the FileUploader view.

  1. //If the file is a "Word Document" file.  
  2. else if (ext == ".doc" || ext == ".docx" || ext == ".rtf")  
  3. {  
  4.     string inputFilePath = ""string outputFilePath = "";  
  5.     inputFilePath = Server.MapPath("~/UploadBooks/Attachments/" + guid +ext);  
  6.     outputFilePath = Server.MapPath("~/UploadBooks/Attachments/" + guid + ".pdf");  
  7.     FinalPath = Server.MapPath("~/UploadBooks/Attachments/" + guid + ".pdf");  
  8.     upload.ExportWordFileToPdf(inputFilePath, outputFilePath);  
  9.     upload.ConvertSingleImage(FinalPath);  
  10.     string str = "../../UploadBooks/Attachments/Preview/" + guid + ".jpg";  
  11.     return Content(str);  
  12. } 

Converting the ppt or pptx file into JPEG file

1. Add the following code to your controller to convert the ppt or pptx file that will come from the FileUploader view directly into JPEG format and finally pass the converted JPEG file back to the FileUploader view. For this add the reference files Microsoft.Office.Interop.PowerPoint.dll and Office.dll (Microsoft Office 12.0 Object Library COM File).

  1. //If the file is a "Power Point" file.  
  2. else if (ext == ".ppt" || ext == ".pptx")  
  3. {  
  4.     string inputFilePath = "";  
  5.     inputFilePath = Server.MapPath("~/UploadBooks/Attachments/" + guid + ext);  
  6.     //outputFilePath = Server.MapPath("~/UploadBooks/Attachments/" + guid + ".pdf");  
  7.     FinalPath = Server.MapPath("~/UploadBooks/Attachments/Preview" + guid + ".jpg");  
  8.     string ExportLocation = Server.MapPath("~/UploadBooks/Attachments/Preview/");  
  9.     Microsoft.Office.Interop.PowerPoint.Application ppApp = new Microsoft.Office.Interop.PowerPoint.Application();  
  10.     //ppApp.Visible = MsoTriState.msoTrue; //To open the ppt file.  
  11.     //ppApp.WindowState = PpWindowState.ppWindowMinimized; //To minimise the opened ppt file.  
  12.     Microsoft.Office.Interop.PowerPoint.Presentations oPresSet = ppApp.Presentations;  
  13.     Microsoft.Office.Interop.PowerPoint._Presentation oPres = oPresSet.Open(inputFilePath,  
  14.     MsoTriState.msoFalse, MsoTriState.msoFalse,  
  15.     MsoTriState.msoFalse);  
  16.     ppApp.ShowWindowsInTaskbar = MsoTriState.msoFalse; //Hiding the application; But it will be displayed always  
  17.     try  
  18.     {  
  19.         Slides objSlides = oPres.Slides; //Getting all the slides  
  20.         for (int i = 1; i < 2; i++) //If you want to convert all the slides into jpg then use "i < objSlides-1" in for loop.  
  21.         {  
  22.            string files = Path.Combine(ExportLocation, string.Format("{0}.{1}", guid, "jpg"));  
  23.            oPres.Slides[i].Export(files, "jpg", 800, 600);  
  24.         }  
  25.     }  
  26.     finally  
  27.     {  
  28.         ppApp.Quit(); //Closing the Powerpoint application. Sometimes it won't work too.  
  29.     }  
  30.     string str = "../../UploadBooks/Attachments/Preview/" + guid + ".jpg";  
  31.     return Content(str);  
  32. } 

Converting the PDF file into JPEG file

1. Add the following code to your controller to convert the PDF file that will come from the FileUploader view directly into JPEG format and finally pass the converted JPEG file back to the FileUploader view.

  1. //If the file is a "PDF" file.  
  2. else if (ext == ".pdf")  
  3. {  
  4.     FinalPath = Server.MapPath("~/UploadBooks/Attachments/" + guid + ext);  
  5.     upload.ConvertSingleImage(FinalPath); //Convert the pdf file into "jpg" file, the code is written in FileUploaderModel.cs  
  6.     string str = "../../UploadBooks/Attachments/Preview/" + guid + ".jpg";  
  7.     return Content(str);  
  8. } 

Converting the htm or html file into JPEG file

1. Add the following code to your controller to convert the htm or html file that will come from the FileUploader view into a PDF and then into JPEG format and finally pass the converted JPEG file back to the FileUploader view.

For this add the class file Html2PDF.cs to the classes folder and add the reference itextsharp.dll file.

  1. else if (ext == ".htm" || ext == ".html")  
  2. {  
  3.     string inputFilePath = ""string outputFilePath = "";  
  4.     inputFilePath = Server.MapPath("~/UploadBooks/Attachments/" + guid+ext);  
  5.     outputFilePath = Server.MapPath("~/UploadBooks/Attachments/" + guid + ".pdf");  
  6.     FinalPath = Server.MapPath("~/UploadBooks/Attachments/" + guid + ".pdf");  
  7.     Html2PDF.Convert(inputFilePath, outputFilePath); //Convert the html file into "pdf" file using Html2PDF.cs  
  8.     upload.ConvertSingleImage(FinalPath); //Convert the pdf file into "jpg" file, the code is written in FileUploaderModel.cs  
  9.     string str = "../../UploadBooks/Attachments/Preview/" + guid + ".jpg";  
  10.     return Content(str);  
  11. } 

Now run your project and enjoy the code.


Similar Articles