Results 1 to 27 of 27

Thread: Upload with json and send response back to form

  1. #1

    Thread Starter
    Junior Member
    Join Date
    Feb 2017
    Posts
    27

    Upload with json and send response back to form

    Hello All;

    I am working on an upload script, that works great.
    It uploads and inserts the data into a database.
    And then lets you know that it was uploaded successfully.

    This is the issue.
    It will not allow me to send a response.write with the image name to the form.

    This is the code.

    Code:
        Protected Sub Page_Load(sender As Object, e As EventArgs)
            Dim postedContext As HttpContext = HttpContext.Current
            Dim file As HttpPostedFile = postedContext.Request.Files(0)
            Dim name As String = file.FileName
    
            Dim binaryWriteArray As Byte() = New Byte(file.InputStream.Length - 1) {}
            file.InputStream.Read(binaryWriteArray, 0, CInt(file.InputStream.Length))
            Dim objfilestream As New FileStream(Server.MapPath(Convert.ToString("uploads1/") & name), FileMode.Create, FileAccess.ReadWrite)
    
            objfilestream.Write(binaryWriteArray, 0, binaryWriteArray.Length)
            objfilestream.Close()
            Dim JaggedArray As String()() = New String(0)() {}
            JaggedArray(0) = New String() {"0", "File was uploaded successfully", name}
            Dim js As New JavaScriptSerializer()
            Dim strJSON As String = js.Serialize(JaggedArray)
            Response.Write(strJSON)
    response.write("Something here") ' This is where the error will happen at
            Response.[End]()
        End Sub
    After it does the Response.Write(strJSON)
    This is where I need to send information back to the form.

    Every time that I try to add a response.write (name)
    It gives me an error in the Browser Console (Chrome F12)

    Uncaught SyntaxError: Unexpected token H in JSON

    Can someone shine some like on how to send Binary and regular data back to the form?
    Thank Carrzkiss

  2. #2
    PowerPoster PlausiblyDamp's Avatar
    Join Date
    Dec 2016
    Location
    Pontypool, Wales
    Posts
    2,458

    Re: Upload with json and send response back to form

    If the response is JSON then the entire response needs to be JSON, could you not make the extra bit of information you return part of the JSON you are returning?

    Other than that I think the only other option would be to return a mime multipart response https://en.wikipedia.org/wiki/MIME#Multipart_messages gives a brief overview of how it would look.

  3. #3

    Thread Starter
    Junior Member
    Join Date
    Feb 2017
    Posts
    27

    Re: Upload with json and send response back to form

    speaking of the JSON, how would I return it as a JSON return?
    That sounds more interesting than the mime.

    It is already returning this part.
    JaggedArray(0) = New String() {"0", "File was uploaded successfully", name}
    Which gives the name of the image.
    But I am needing something that can be used in a <input type="hidden" name="imageID" value="Get the value here"/> (If possible)

  4. #4
    PowerPoster PlausiblyDamp's Avatar
    Join Date
    Dec 2016
    Location
    Pontypool, Wales
    Posts
    2,458

    Re: Upload with json and send response back to form

    The code
    Code:
            Dim JaggedArray As String()() = New String(0)() {}
            JaggedArray(0) = New String() {"0", "File was uploaded successfully", name}
            Dim js As New JavaScriptSerializer()
            Dim strJSON As String = js.Serialize(JaggedArray)
            Response.Write(strJSON)
    is already turning your jagged array into Json so you are already doing that bit. You could just add the extra information you want to return to the jagged array and carry on serializing it the same way, although it might be better to create a simple class that has properties to hold the bits of information you wish to return an serialze that rather than using the string array.

    I would also recommend not using the JavaScriptSerializer, it is generally better to use something like the Newtonsoft json parser (even the MS documentation at https://msdn.microsoft.com/en-us/lib...v=vs.110).aspx says the same thing)

  5. #5

    Thread Starter
    Junior Member
    Join Date
    Feb 2017
    Posts
    27

    Re: Upload with json and send response back to form

    I was doing some research on JSON and found the Newtonsoft JSON parser earlier.
    However, would it work with this project?

    This is the script with the upload function that I am using.
    http://www.cffcs.com/stuff/uploads.zip

  6. #6

    Thread Starter
    Junior Member
    Join Date
    Feb 2017
    Posts
    27

    Re: Upload with json and send response back to form

    After installing the JSON.NET package, the only thing I was able to do was to convert one line.

    Imports Newtonsoft.Json

    From This:
    Dim js As New JavaScriptSerializer()
    To This:
    Dim js As New JsonSerializer()

    This line is giving me an error, of (Overload resolution failed because no accessible "Serialize" accepts this number of arguments)
    Dim strJSON As String = js.Serialize(JaggedArray)

    I have tried to find something that will help me to resolve this issue, so I can at least get this part working with the JSON.NET plugin, but there seems to be very little resources, at least for vb.net. A lot for C#.

  7. #7
    PowerPoster PlausiblyDamp's Avatar
    Join Date
    Dec 2016
    Location
    Pontypool, Wales
    Posts
    2,458

    Re: Upload with json and send response back to form

    Easiest way using Json.Net would be
    Code:
    Dim strJSON as String = JsonConvert.SerializeObject(product)
    Is the code in script.js
    Code:
         uploadFinished: function (i, file, response) {
                // Pass the template to createImage()
                createImage(file, template);
    
                $.data(file).addClass('done');
    
                // see if upload failed
                if (1 === parseInt(response[0][0], 10)) {
                    alert(response[0][1]);
                    return;
                }
    required to be done in that way or are you after any way of getting a result back to the browser that can be parsed in javascript?

  8. #8

    Thread Starter
    Junior Member
    Join Date
    Feb 2017
    Posts
    27

    Re: Upload with json and send response back to form

    Added this
    Dim strJSON as String = JsonConvert.SerializeObject(JaggedArray)
    Works good.

    No, it is not required to be done that way.
    I had another person that was assisting me in trying to pass the data, and he was also checking if the file succedded as well.

    What I need is a way to send the [ImageName.jpg] back to the form, and have it so i can update the record once it is inserted into the database.
    That is what I need to accomplish.

  9. #9
    PowerPoster PlausiblyDamp's Avatar
    Join Date
    Dec 2016
    Location
    Pontypool, Wales
    Posts
    2,458

    Re: Upload with json and send response back to form

    Messing with things like jagged arrays can really make your life difficult, if you are dealing with javascript it is much easier to just work with JSON and avoid parsing out the array.

    Just to give you an idea of how I would have done this....

    I just added a quick class to the Default.aspx.vb (in reality I could have put it anywhere in the project)
    Code:
    Public Class DemoResponse
        Property Message As String
        Property Name As String
        Property FileCount As Integer
        Property Code As Integer
    End Class
    I then updated the Page_Load event to be
    Code:
     Protected Sub Page_Load(sender As Object, e As EventArgs)
            Dim postedContext As HttpContext = HttpContext.Current
            Dim file As HttpPostedFile = postedContext.Request.Files(0)
            Dim name As String = file.FileName
    
            Dim binaryWriteArray As Byte() = New Byte(file.InputStream.Length - 1) {}
            file.InputStream.Read(binaryWriteArray, 0, CInt(file.InputStream.Length))
            Dim objfilestream As New FileStream(Server.MapPath(Convert.ToString("uploads/") & name), FileMode.Create, FileAccess.ReadWrite)
    
            objfilestream.Write(binaryWriteArray, 0, binaryWriteArray.Length)
            objfilestream.Close()
    
            'Changes are here
            Dim dr As New DemoResponse With {
            .Code = 0,
            .FileCount = CInt(Session("fileCount")),
            .Message = "File was uploaded successfully",
            .Name = name
            }
    
            Dim strJSON As String = JsonConvert.SerializeObject(dr)
            Response.Write(strJSON)
            Response.[End]()
    which will create an instance of the DemoResponse class, sets a few properties and then serializes it to JSON and returns it.

    The important bit of the script.js is now
    Code:
     uploadFinished: function (i, file, response) {
                // Pass the template to createImage()
                createImage(file, template);
    
                $.data(file).addClass('done');
    
                // see if upload failed
     
                if (1 === parseInt(response.Code)) {
                    alert(response.Message);
                    return;
                }
    
                // update the file upload tracker
                ++fileCount;
    
                // verify the that you are getting the correct file count and file names on the console
                console.log("fileCount=" + fileCount);
                console.log("response=" + response);
            },
    Notice this skips the whole nested array parsing and uses the json directly.

    I have attached the modified version, you just need to add the Newtonsoft.Json package and it should work fine.
    Attached Files Attached Files

  10. #10

    Thread Starter
    Junior Member
    Join Date
    Feb 2017
    Posts
    27

    Re: Upload with json and send response back to form

    How do I add the "Newtonsoft.Json package"?
    I have it installed, just not sure how to add it to a new web site.
    Last edited by carrzkiss; Feb 27th, 2017 at 01:54 PM.

  11. #11
    PowerPoster PlausiblyDamp's Avatar
    Join Date
    Dec 2016
    Location
    Pontypool, Wales
    Posts
    2,458

    Re: Upload with json and send response back to form

    Right click on the solution and go to manage nuget packages (the name might be different depending on the version of VS), then just search for it and install.

  12. #12

    Thread Starter
    Junior Member
    Join Date
    Feb 2017
    Posts
    27

    Re: Upload with json and send response back to form

    I am running VS Community 2015.
    I right click on the Web Site.
    Choose [Manage Nugent Packages...]
    And it shows as being installed.
    Name:  Package.jpg
Views: 934
Size:  22.8 KB

  13. #13
    PowerPoster PlausiblyDamp's Avatar
    Join Date
    Dec 2016
    Location
    Pontypool, Wales
    Posts
    2,458

    Re: Upload with json and send response back to form

    The code should work then, I can't make out the error message in that screenshot though. Might be worth removing it and reinstalling it to see if that helps.

  14. #14

    Thread Starter
    Junior Member
    Join Date
    Feb 2017
    Posts
    27

    Re: Upload with json and send response back to form

    That did it.
    Uninstalling it, and re-installing it worked.
    It runs and uploads the image.

    Now, how would I use this to my advantage for retrieving the values and sending them back to the form, for further processing?

  15. #15
    PowerPoster PlausiblyDamp's Avatar
    Join Date
    Dec 2016
    Location
    Pontypool, Wales
    Posts
    2,458

    Re: Upload with json and send response back to form

    It depends what you want to do with them exactly, the code in script.js now has access to the properties of the returned object and you could use it to manipulate the form in whatever way you wanted. Is there any particular thing you had in mind regarding what you wanted to do with the form?

    Also, just out of interest, is there a reason the form is an asp file as there doesn't seem to be any code in there and it would work just the same as a html file?

  16. #16

    Thread Starter
    Junior Member
    Join Date
    Feb 2017
    Posts
    27

    Re: Upload with json and send response back to form

    .asp (Nope, was just testing something early on, and just left it as is.)

    What I want to do, and have tried before, but not with the new JSON, is to send the name of the Image file, back to the form.
    Which would be done in the .js file, that I know.
    But how would I get the name of the file to show up inside of a form field?
    <input type="text" name="ImageName" value="image.jpg" />

    Once I can successfully get the value of the image sent to the form, then I will be able to use it to challenge the database to update the image title, description, etc...

    That is what I have been after, that is what I have been trying to get accomplished since I started on this about a week ago.
    I have come a long ways with the actual project, just cannot get that image name sent back to the form, that has been choking me.

  17. #17
    PowerPoster PlausiblyDamp's Avatar
    Join Date
    Dec 2016
    Location
    Pontypool, Wales
    Posts
    2,458

    Re: Upload with json and send response back to form

    Somewhere on the .asp form just add an input control
    Code:
       <input id="fileName" type="text" />
    in the script.js just do something like
    Code:
    if (1 === parseInt(response.Code)) {
        alert(response.Message);
        return;
        }
    
    //Add this line
    $("#fileName").val(response.Name);
    and it should update the input control with the filename of the added file.

  18. #18

    Thread Starter
    Junior Member
    Join Date
    Feb 2017
    Posts
    27

    Re: Upload with json and send response back to form

    did not work.
    I have this in an asp file that grabs all the form fields on Submit.
    And it is not catching anything in that field.
    Just the name I gave it, and it is blank.

    commas added it into the JS "template" area, and it is only applying commas.
    So, if I add three images, it returns three comma's. , , ,
    So, at least that is something, but still no go.

    Code:
    <%
        for each item in Request.Form
        Response.Write "<p>" & item & " = " & Request.Form( item ) & "</p>"
    next
       %>

  19. #19
    PowerPoster PlausiblyDamp's Avatar
    Join Date
    Dec 2016
    Location
    Pontypool, Wales
    Posts
    2,458

    Re: Upload with json and send response back to form

    The code I posted worked at this end, after dragging the image the input field displayed the file name - could you post the code you are using and I will see if I can figure out what is happening.

  20. #20

    Thread Starter
    Junior Member
    Join Date
    Feb 2017
    Posts
    27

    Re: Upload with json and send response back to form

    OK, I got it to work.
    Something got messed up in the code, and it did not work.

    OK, adding it into the form itself, will only give ONE instance of the field, of which will only provide one image name.
    Now.
    If I put it in the js file, it will create multiple instances, depending on the amount of images placed on the stage.
    However, it would only put the name in the first field, so I changed it to a "Class" instead.
    Now, it placing the name in each of the instances of the field, however. It is the identical name.

    In the UploadFinished.
    Code:
    $(".fileName").val(response.Name);
    In the Template
    Code:
    '<input class="fileName" name="ImageName" type="text" />'+
    Need a way to have each image, have its own name in its own field.

  21. #21
    PowerPoster PlausiblyDamp's Avatar
    Join Date
    Dec 2016
    Location
    Pontypool, Wales
    Posts
    2,458

    Re: Upload with json and send response back to form

    It is a bit rough and the result is ugly but...

    In the .asp page add
    Code:
    <div id="test">
                
    </div>
    and change the script to now have
    Code:
    // see if upload failed 
    if (1 === parseInt(response.Code)) {
        alert(response.Message);
        return;
    }
    
    // update the file upload tracker
    ++fileCount;
    
    var name = "input" + fileCount;
    var newInput = $("<input type=\"text\" id=\"" + name + "\" name=\"" + name + "\" value=\"" + response.Name + "\" />");   
    $("#test").after(newInput);
    and you should see it create a textbox for each file name.

  22. #22

    Thread Starter
    Junior Member
    Join Date
    Feb 2017
    Posts
    27

    Re: Upload with json and send response back to form

    The images names show up, that is awesome!
    Now, "HOW" do I pass that to the processing page?
    I tried to post it, to the test post, and it did not grab it.

    Code:
    <%
        for each item in Request.Form
        Response.Write "<p>" & item & " = " & Request.Form( item ) & "</p>"
    next
       %>

  23. #23
    PowerPoster PlausiblyDamp's Avatar
    Join Date
    Dec 2016
    Location
    Pontypool, Wales
    Posts
    2,458

    Re: Upload with json and send response back to form

    Which page is the processing page and how are you submitting the data to it?

  24. #24

    Thread Starter
    Junior Member
    Join Date
    Feb 2017
    Posts
    27

    Re: Upload with json and send response back to form

    IT WORKS!!!!!!!!!
    I had the DIV on the outside of the form.
    Now to test and make sure it is going to work in the actual project.
    PlausiblyDamp , you are a life saver my friend.
    Thank you so very much for the time you took to help me out on this issue.
    I cannot thank you enough, for this one.
    You ROCK!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
    Last edited by carrzkiss; Mar 1st, 2017 at 09:30 PM. Reason: changed "think" to "thank"

  25. #25
    PowerPoster PlausiblyDamp's Avatar
    Join Date
    Dec 2016
    Location
    Pontypool, Wales
    Posts
    2,458

    Re: Upload with json and send response back to form

    No problem, glad to help.

  26. #26

    Thread Starter
    Junior Member
    Join Date
    Feb 2017
    Posts
    27

    Re: Upload with json and send response back to form

    Is there a way to Accept a post as Answer?
    Or
    Is it just the [rate this post] option?
    I already did that part.

  27. #27
    PowerPoster PlausiblyDamp's Avatar
    Join Date
    Dec 2016
    Location
    Pontypool, Wales
    Posts
    2,458

    Re: Upload with json and send response back to form

    You should be able to mark the Thread as resolved, other than that just rating the post is enough as far as I am aware.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width