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.

namespace FileUploader.Controllers

public class HomeController : Controller

{

    // GET: /Home/

public ActionResult FileUploader()

{

    return View();

}

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.

@{<br /> ViewBag.Title = "FileUploader";

         Layout = "~/Views/Shared/_Layout.cshtml";

}

<h2>

    FileUploader</h2>

@using (Html.BeginForm())

{

    <div>

        <img src="" width="100" height="100" id="msg" />

    </div>

    <div>

        <p id="message">

        </p>

    </div>

    <input type="file" name="file" id="file" />

    <input type="button" class="clickClass" value="submit" id="submit" />

}

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.

namespace FileUploader.Models

{

    public class FileUploaderModel

    {

        //public string guid { get; set; }

        PdfToImage.PDFConvert PdfConverter = new PdfToImage.PDFConvert();

        //Convert the pdf into Single Image.

        public void ConvertSingleImage(string filename)

        {

             try

             {

                 PdfConverter.RenderingThreads = 5;

                 PdfConverter.TextAlphaBit = 4;

                 PdfConverter.OutputToMultipleFile = false;

                 PdfConverter.FirstPageToConvert = -1;

                 PdfConverter.LastPageToConvert = -1;

                 PdfConverter.FitPage = false;

                 PdfConverter.JPEGQuality = 10;

                 PdfConverter.OutputFormat = "jpeg";

                 System.IO.FileInfo input = new FileInfo(filename);

                 string[] str = input.Name.Split('.');

                 string output = string.Format("{0}\\{1}{2}", input.Directory + "\\Preview", str[0].ToString(), ".jpg");

                 while (System.IO.File.Exists(output))

                 {

                     File.Delete(output);

                     output = string.Format("{0}\\{1}{2}", input.Directory + "\\Preview", str[0].ToString(), ".jpg");

                 }

            }

        }

        catch (Exception ex)

        {

        }

        return;

    }

}

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.

[HttpPost]

public ActionResult FileUploader(FileUploaderModel upload)

{

    string guid = Guid.NewGuid().ToString();

    //upload.guid = guid;

    string msg = "Something went wrong, Your file was not uploaded.";

    HttpPostedFileBase file = Request.Files[0];

    string FinalPath = "";

    if (file != null && file.ContentLength > 0)

    {

        var fileName = Path.GetFileName(file.FileName); // extract only the fielname

        var ext = Path.GetExtension(fileName.ToLower()); //extract only the extension of filename and then convert it into lower case.

        //var fileNameWithoutExt = Path.GetFileNameWithoutExtension(fileName);

        var path = Server.MapPath("~/UploadBooks/Attachments/" + guid + ext);

        file.SaveAs(path);

        if (ext == ".txt") //If the file is a "text" file.

        {

           string filePath = "";

           string filePath12 = "";

           filePath = Server.MapPath("~/UploadBooks/Attachments/" + guid + ext);

           filePath12 = Server.MapPath("~/UploadBooks/Attachments/");

           FinalPath = Server.MapPath("~/UploadBooks/Attachments/" + guid + ".pdf");

           TextPDF.PdfWriter pdfWriter = new TextPDF.PdfWriter(842.0f, 1190.0f, 10.0f, 10.0f);

           pdfWriter.Getfilename(guid, filePath12); //Convert the "txt" file into "pdf" file

           if (filePath.Length > 0)

           pdfWriter.Write(filePath); //Store the converted pdf file into Attachments folder

           upload.ConvertSingleImage(FinalPath); //Convert the pdf file into "jpg" file, the code is written in FileUploaderModel.cs

           string str = "../../UploadBooks/Attachments/Preview/" + guid + ".jpg";

           return Content(str);

        }

    }

} 

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.

<script type="text/javascript">

    document.getElementById('submit').onclick = function () {

        var formdata = new FormData(); //FormData object

        var fileInput = document.getElementById('file');

        //Iterating through each files selected in fileInput

        for (i = 0; i < fileInput.files.length; i++) {

            //Appending each file to FormData object

            formdata.append(fileInput.files[i].name, fileInput.files[i]);

        }

        //Creating an XMLHttpRequest and sending

        var xhr = new XMLHttpRequest();

        xhr.open('POST', '/Home/FileUploader');

        xhr.send(formdata);

        xhr.onreadystatechange = function () {

            if (xhr.readyState == 4 && xhr.status == 200) {

                var msg = "Your file was successfully uploaded";

                $("#msg").attr('src', xhr.responseText);

                $("#message").text(msg)

            }

        }

        return false;

    }

</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.

//Method to convert the Excel file into Pdf

public bool ExportWorkbookToPdf(string workbookPath, string outputPath)

{

    // If either required string is null or empty, stop and bail out

    if (string.IsNullOrEmpty(workbookPath) || string.IsNullOrEmpty(outputPath))

    {

        return false;

     }

     // Create COM Objects

     Microsoft.Office.Interop.Excel.Application excelApplication;

     Microsoft.Office.Interop.Excel.Workbook excelWorkbook;

     excelApplication = new Microsoft.Office.Interop.Excel.Application(); // Create new instance of Excel

     excelApplication.ScreenUpdating = false; // Make the process invisible to the user

     excelApplication.DisplayAlerts = false; // Make the process silent

     excelWorkbook = excelApplication.Workbooks.Open(workbookPath); // Open the workbook that you wish to export to PDF

     // If the workbook failed to open, stop, clean up, and bail out

     if (excelWorkbook == null)

     {

         excelApplication.Quit();

         excelApplication = null;

         excelWorkbook = null;

         return false;

     }

     var exportSuccessful = true;

     try

     {

         // Call Excel's native export function (valid in Office 2007 and Office 2010, AFAIK)

         excelWorkbook.ExportAsFixedFormat(Microsoft.Office.Interop.Excel.XlFixedFormatType.xlTypePDF, outputPath);

     }

     catch (System.Exception ex)

     {

         // Mark the export as failed for the return value...

         exportSuccessful = false;

         // Do something with any exceptions here, if you wish...

         // MessageBox.Show...

     }

     finally

     {

          // Close the workbook, quit the Excel, and clean up regardless of the results...

          excelWorkbook.Close();

          excelApplication.Quit();

          excelApplication = null;

          excelWorkbook = null;

      }

      return exportSuccessful;

 

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.

//If the file is a "Excel" file.

else if (ext == ".xls" || ext == ".xlsx")

{

    string inputFilePath = ""; string outputFilePath = "";

    inputFilePath = Server.MapPath("~/UploadBooks/Attachments/" + guid +ext);

    outputFilePath = Server.MapPath("~/UploadBooks/Attachments/" + guid + ".pdf");

    FinalPath = Server.MapPath("~/UploadBooks/Attachments/" + guid + ".pdf");

    upload.ExportWorkbookToPdf(inputFilePath, outputFilePath); //Convert the Excel file into "pdf" file

    upload.ConvertSingleImage(FinalPath); //Convert the pdf file into "jpg" file, the code is written in FileUploaderModel.cs

    string str = "../../UploadBooks/Attachments/Preview/" + guid + ".jpg";

    return Content(str);

}

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 .

//Method to convert the Word file into Pdf

public Microsoft.Office.Interop.Word.Document wordDocument { get; set; }

public bool ExportWordFileToPdf(string workbookPath, string outputPath)

{

    Microsoft.Office.Interop.Word.Application appWord = new Microsoft.Office.Interop.Word.Application();

    wordDocument = appWord.Documents.Open(workbookPath);

    var exportSuccessful = true;

    try

    {

        wordDocument.ExportAsFixedFormat(outputPath, WdExportFormat.wdExportFormatPDF);

    }

    catch (System.Exception ex)

    {

         // Mark the export as failed for the return value...

         exportSuccessful = false;

        // Do something with any exceptions here, if you wish...

        // MessageBox.Show...

    }

    finally

    {

         // Close the wordDocument, quit the Document, and clean up regardless of the results...

         ((_Document)wordDocument).Close();

         ((_Application)appWord).Quit();

         appWord = null;

         wordDocument = null;

    }

    return exportSuccessful;

} 

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.

//If the file is a "Word Document" file.

else if (ext == ".doc" || ext == ".docx" || ext == ".rtf")

{

    string inputFilePath = ""; string outputFilePath = "";

    inputFilePath = Server.MapPath("~/UploadBooks/Attachments/" + guid +ext);

    outputFilePath = Server.MapPath("~/UploadBooks/Attachments/" + guid + ".pdf");

    FinalPath = Server.MapPath("~/UploadBooks/Attachments/" + guid + ".pdf");

    upload.ExportWordFileToPdf(inputFilePath, outputFilePath);

    upload.ConvertSingleImage(FinalPath);

    string str = "../../UploadBooks/Attachments/Preview/" + guid + ".jpg";

    return Content(str);

}<br />

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).

//If the file is a "Power Point" file.

else if (ext == ".ppt" || ext == ".pptx")

{

    string inputFilePath = "";

    inputFilePath = Server.MapPath("~/UploadBooks/Attachments/" + guid + ext);

    //outputFilePath = Server.MapPath("~/UploadBooks/Attachments/" + guid + ".pdf");

    FinalPath = Server.MapPath("~/UploadBooks/Attachments/Preview" + guid + ".jpg");

    string ExportLocation = Server.MapPath("~/UploadBooks/Attachments/Preview/");

    Microsoft.Office.Interop.PowerPoint.Application ppApp = new Microsoft.Office.Interop.PowerPoint.Application();

    //ppApp.Visible = MsoTriState.msoTrue; //To open the ppt file.

    //ppApp.WindowState = PpWindowState.ppWindowMinimized; //To minimise the opened ppt file.

    Microsoft.Office.Interop.PowerPoint.Presentations oPresSet = ppApp.Presentations;

    Microsoft.Office.Interop.PowerPoint._Presentation oPres = oPresSet.Open(inputFilePath,

    MsoTriState.msoFalse, MsoTriState.msoFalse,

    MsoTriState.msoFalse);

    ppApp.ShowWindowsInTaskbar = MsoTriState.msoFalse; //Hiding the application; But it will be displayed always

    try

    {

        Slides objSlides = oPres.Slides; //Getting all the slides

        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.

        {

           string files = Path.Combine(ExportLocation, string.Format("{0}.{1}", guid, "jpg"));

           oPres.Slides[i].Export(files, "jpg", 800, 600);

        }

    }

    finally

    {

        ppApp.Quit(); //Closing the Powerpoint application. Sometimes it won't work too.

    }

    string str = "../../UploadBooks/Attachments/Preview/" + guid + ".jpg";

    return Content(str);

}

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.

//If the file is a "PDF" file.

else if (ext == ".pdf")

{

    FinalPath = Server.MapPath("~/UploadBooks/Attachments/" + guid + ext);

    upload.ConvertSingleImage(FinalPath); //Convert the pdf file into "jpg" file, the code is written in FileUploaderModel.cs

    string str = "../../UploadBooks/Attachments/Preview/" + guid + ".jpg";

    return Content(str);

}

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.

else if (ext == ".htm" || ext == ".html")

{

    string inputFilePath = ""; string outputFilePath = "";

    inputFilePath = Server.MapPath("~/UploadBooks/Attachments/" + guid+ext);

    outputFilePath = Server.MapPath("~/UploadBooks/Attachments/" + guid + ".pdf");

    FinalPath = Server.MapPath("~/UploadBooks/Attachments/" + guid + ".pdf");

    Html2PDF.Convert(inputFilePath, outputFilePath); //Convert the html file into "pdf" file using Html2PDF.cs

    upload.ConvertSingleImage(FinalPath); //Convert the pdf file into "jpg" file, the code is written in FileUploaderModel.cs

    string str = "../../UploadBooks/Attachments/Preview/" + guid + ".jpg";

    return Content(str);

} 

Now run your project and enjoy the code.