Click here to Skip to main content
15,891,951 members
Please Sign up or sign in to vote.
3.50/5 (2 votes)
Hello all.

I am using a drag-drop functionality + simple file upload (html <file> control) to auto upload pdf files as a user drops or choose a pdf file. For this work i opted to use javascript and asp.net4.0 (not jquery).

When user drops the file, i grab it and send this file using xmlhttpobject's send method to a Http generic handler (written in vb.net).

I am getting the dropped file as stream( in handler code )using Request.InputStream.

The problem is, when i write this strem to filestream and creats a pdf file, the newly created file has stream code written into it. (not graphics of PDF but the stream machine understandable code). I just need that the uploaded file will look same the dropped file.

I am assuming that i am missing something content-type or encoding specifications while creating file. I do not know how to resolve this. Please help me, i am copying all code involves in this.

Javascript Code:

This Function runs when a file dragged or choosed:

JavaScript
function FileSelectHandler(e) {
        // cancel event and hover styling
        FileDragHover(e);
        // fetch FileList object
        var files = e.target.files || e.dataTransfer.files;

        // process all File objects
        for (var i = 0, f; f = files[i]; i++) {
            UploadFile(f);//see below
        }
    }

//////////////////////////////////////////////////////////////////////////////////////////////
This is the main function that uploads the file
//////////////////////////////////////////////////////////////////////////////////////////////
function UploadFile(file) {
    var xhr = new Async();//function that returns xmlhttprequest object,see below
    var path;
    if (xhr.upload) {
        var url = "X_Upload.ashx";
        xhr.open("post", url, true);
        xhr.setRequestHeader("X_FILENAME", file.name);
        xhr.setRequestHeader("Content-Type", file.type);
        xhr.onreadystatechange = function () {
            if (xhr.readyState == 4) {
                var response = eval("(" + xhr.responseText + ")");
                path = response; alert(path);
            }
        }
        xhr.send(file);
    }
}
//////////////////////////////////////////////////////////////////////////////////////////////
function Async() {

        var objXMLHttp = null;
        if (window.XMLHttpRequest) {

            objXMLHttp = new XMLHttpRequest();
        }
        else if (window.ActiveXObject) {
            try {
                objXMLHttp = new ActiveXObject("Msxml2.XMLHTTP.4.0");
            }
            catch (e) { try { objXMLHttp = new ActiveXObject("MSXML2.XMLHTTP"); } catch (e) { try { objXMLHttp = new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) { objXMLHttp = null; } } }
        }
        return objXMLHttp;
    }
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////

Handler, X_Upload.ashx  code: //please remember that the uploaded file is only .pdf

<%@ WebHandler Language="VB" Class="X_Upload" %>

Imports System
Imports System.IO
Imports System.Web

Public Class X_Upload : Implements IHttpHandler, IRequiresSessionState
    Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
        Dim folderName As String

        If Not context.Session("CurrentProofFolder") Is Nothing Then
            folderName = context.Session("CurrentProofFolder")
        Else
            folderName = Guid.NewGuid.ToString
            context.Session("CurrentProofFolder") = folderName
        End If

        Dim rootPath As String = context.Server.MapPath("~")

        Dim currentDir As String = rootPath & "\Files\" & folderName

        If Not Directory.Exists(currentDir) Then
            Directory.CreateDirectory(currentDir)
        End If



        Dim filePath As String = currentDir & "\" & context.Request.Headers("X_FILENAME")

        Dim fs As New FileStream(filePath, FileMode.Create, FileAccess.ReadWrite)



        Dim fileData As Byte() = New Byte(context.Request.InputStream.Length) {}

        ' Read the file into a byte array
        context.Request.InputStream.Read(fileData, 0, context.Request.InputStream.Length)

        fs.Write(fileData, 0, context.Request.InputStream.Length)

        fs.Dispose()
    End Sub
    Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
        Get
            Return False
        End Get
    End Property

End Class

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
Please also take a look, how the pdf is looking after creation, I am pasting only few lines inside the created pdf file as the files has 1500 lines.


%PDF-1.5
%âãÏÓ
1 0 obj
<</Metadata 2 0 R/OCProperties<</D<</ON[5 0 R]/Order 6 0 R/RBGroups[]>>/OCGs[5 0 R]>>/Pages 3 0 R/Type/Catalog>>
endobj
2 0 obj
<</Length 50618/Subtype/XML/Type/Metadata>>stream
<?xpacket begin="" id="W5M0MpCehiHzreSzNTczkc9d"?>
<x:xmpmeta xmlns:x="adobe:ns:meta/" x:xmptk="Adobe XMP Core 5.0-c060 61.134777, 2010/02/12-17:32:00        ">
   <rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#">
      <rdf:Description rdf:about=""
            xmlns:dc="http://purl.org/dc/elements/1.1/">
         <dc:format>application/pdf</dc:format>
         <dc:title>
            <rdf:Alt>
               <rdf:li xml:lang="x-default">26823_artproof_1</rdf:li>
            </rdf:Alt>
         </dc:title>
      </rdf:Description>
      <rdf:Description rdf:about=""
            xmlns:xmp="http://ns.adobe.com/xap/1.0/"
            xmlns:xmpGImg="http://ns.adobe.com/xap/1.0/g/img/">
         <xmp:MetadataDate>2012-04-18T03:49:52+08:00</xmp:MetadataDate>
         <xmp:ModifyDate>2012-04-18T03:49:52+08:00</xmp:ModifyDate>
         <xmp:CreateDate>2012-04-18T03:49:52+09:00</xmp:CreateDate>
         <xmp:CreatorTool>Adobe Illustrator CS5.1</xmp:CreatorTool>
         <xmp:Thumbnails>
            <rdf:Alt>
               <rdf:li rdf:parseType="Resource">
                  <xmpGImg:width>256</xmpGImg:width>
                  <xmpGImg:height>256</xmpGImg:height>
                  <xmpGImg:format>JPEG</xmpGImg:format>



Please help me to create the actual pdf file, this is very important.

Thank you all for your kind help.

Praveen
Posted
Updated 26-Apr-12 18:56pm
v6
Comments
Sergey Alexandrovich Kryukov 26-Apr-12 23:21pm    
Reason for my vote of 2
Code dump. Where is a question?
--SA
praveen4463 26-Apr-12 23:59pm    
Hello,

Thanks for your interest.

I am not sure i understood exactly what you asked? If you did not understand my problem, here is a quick overview.
I am uploading pdf file after user drags it on web page. I use xmlhttprequest object to send the dragged file to server httphandler. the code of handler is written above.
What happens, when i write inputstream to file, newly created file doesn't seem to be a PDF. It had only raw stream written into it. I want it should look same like the uploaded file. (uploaded file has graphic) I also pasted the code written into pdf.
Can you please tell me where i am going wrong?

Praveen

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900