locked
Sending images to new page! Using forms or whatever! RRS feed

  • Question

  • User895691971 posted

    Hi,

    I wanted to use Ajax as the basic element for my website! Its going great, but there is an issue. Image! How to send the image file to the next page? On the current page I can use 

    WebImage

    and its properties, to check whether image is present, and then to upload it and save! 

    But how can I do that when I am sending just names to the file? Should I upload the image on current page? But that will require a submit! I don't want to submit, as if I do there would have been no need of ajax code for that! Just a simple submit could have made it.

    But I want to do that with ajax, any help? For javascript, for ajax! Or some links. Thanks

    Sunday, July 28, 2013 3:25 AM

Answers

  • User-821857111 posted

    To upload files, your form needs an enctype of multipart/form-data, and it needs an action pointing to the "new" page, and it needs to have its method set to POST (GET is the default if no method is specified). Here is a sample based on the demo at the site I linked to:

    AjaxfileUpload.cshtml:

    @{
        
    }
    
    <!DOCTYPE html>
    
    <html lang="en">
        <head>
            <meta charset="utf-8" />
            <title></title>
            <style>
                body { padding: 30px }
                form { display: block; margin: 20px 0; background: #eee; border-radius: 10px; padding: 15px; width: 370px; }
                .progress { ; width:400px; border: 1px solid #ddd; padding: 1px; border-radius: 3px; }
                .bar { background-color: #B4F5B4; width:0%; height:20px; border-radius: 3px; }
                .percent { ; display:inline-block; top:3px; left:48%; }
            </style>
            <script type="text/javascript" src="/Scripts/jquery-1.8.3.min.js"></script>
            <script src="/Scripts/jquery.form.min.js"></script>
    <script>
        $(function () {
            var bar = $('.bar');
            var percent = $('.percent');
            var status = $('#status');
    
            $('form').ajaxForm({
                beforeSend: function () {
                    status.empty();
                    var percentVal = '0%';
                    bar.width(percentVal)
                    percent.html(percentVal);
                },
                uploadProgress: function (event, position, total, percentComplete) {
                    var percentVal = percentComplete + '%';
                    bar.width(percentVal)
                    percent.html(percentVal);
                },
                success: function () {
                    var percentVal = '100%';
                    bar.width(percentVal)
                    percent.html(percentVal);
                },
                complete: function (xhr) {
                    status.html(xhr.responseText.trim());
                }
            });
        });
    
    </script>
        </head>
        <body>
            <h1>File Upload Progress Demo @DateTime.Now</h1>
    	
    	<form action="AjaxFileUpload2/" method="post" enctype="multipart/form-data">
                <input type="file" name="myfile"><br>
                <input type="submit" value="Upload File to Server">
            </form>
        
            <div class="progress">
                <div class="bar"></div >
                <div class="percent">0%</div >
            </div>
        
            <div id="status"></div>
        </body>
    </html>
    


    AjaxfileUpload2.cshtml:

    @{
        var filename = "nothing";
        try{
            if(Request.Files.Count > 0){
                filename = Request.Files[0].FileName;
            }
        }
        catch(HttpException ex){
            filename = "Upload too large";
        }
    }
    @filename



    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, July 29, 2013 3:09 PM
  • User-821857111 posted

    You can get jquery from here: http://jquery.com

    You can get the form plugin from the link I posted in the other reply.

    till now I was using that old Ajax method!

    As I pointed out a few weeks ago, no one does that anymore.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, July 29, 2013 4:59 PM
  • User753101303 posted

    You could try something such as http://www.west-wind.com/weblog/posts/2012/Mar/06/Using-the-HTML5-input-typefile-multiplemultiple-Tag-in-ASPNET :

    for (int i = 0; i < Request.Files.Count; i++) {     HttpPostedFileBase file = Request.Files[i];  etc...

    (it just loops on the Request.Files collection). Note that for this to happen, the input type="file" tag uses the multiple="multiple" attribute (and the browser must support it). Another option is to show multiple input type="file" tags...

     

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, July 30, 2013 7:08 AM

All replies

  • User379720387 posted

    I am no entirely sure what you are doing, but you could send the image id to the next page.

    Or, you could revise your code so there is not a second page to go to.

    Or, you could reconsider your all Ajax approach.

    Or, make an exception here on these two pages.

    Etc.

    Sunday, July 28, 2013 10:27 AM
  • User895691971 posted

    I wnt to upload images via ajax, but I guess thats not possible! Is it?

    Sunday, July 28, 2013 10:33 AM
  • User753101303 posted

    Hi,

    WebImage is a server side class. I suspect that you are trying to do something that won't work (it happens for beginner if you don't have a clear idea of what runs server side and client side as in dev mode you are usually using a single machine that is both the client and server but once deployed you realize it doesn't work as the client and server are not the same machine).

    You can upload files uisng AJAX for example using http://www.asp.net/ajaxLibrary/AjaxControlToolkitSampleSite/AsyncFileUpload/AsyncFileUpload.aspx

    If using WebImage to access client side images keep in mind it won't work once the client and server machine are not the same box...

    Sunday, July 28, 2013 10:53 AM
  • User895691971 posted

    I do have idea about what's server side and what's client side!

    I just wanted to know, what should one do while uploading pictures via Ajax!

    Sunday, July 28, 2013 11:22 AM
  • User753101303 posted

    As you said that you were using the "WebImage" class to check for "file existence" and talked about uploading files, I wanted to make sure of this. Sorry.

    You could try http://davidsonsousa.net/en/post/how-to-upload-a-file-using-mvc-3-and-ajax or http://stackoverflow.com/questions/7912844/asp-net-mvc-ajax-upload-solution talks about third party component.

    To summarize if supported by the browser, the file API allows to get the  content of the a selected user file. You can then send this content using the XMLHttpRequest object and to track how much you sent to display a progress bar. Later you could add drag drop support. If the needed API is not supported by the browser you'll have to fallback to a plain old post (do you already have somehting such as http://www.asp.net/web-pages/tutorials/files,-images,-and-media/working-with-files in place ?)

     

    Monday, July 29, 2013 4:48 AM
  • User38443587 posted

    Hello,

    I’m afraid that we can’t send image via ajax, because js can’t read the file into binary. But we can use ajaxtoolkit to send image with no refresh.

    How to add ajax toolkit? Please refer :

    http://blogs.msdn.com/b/webdev/archive/2009/05/26/using-microsoft-ajax-control-toolkit-with-visual-studio-10-beta-1.aspx<!--?xml:namespace prefix = "o" ns = "urn:schemas-microsoft-com:office:office" /--><o:p></o:p>

    <o:p></o:p>

    How to use ajax toolkit? Please refer:

    http://www.aspsnippets.com/Articles/Display-image-after-upload-without-page-refresh-or-postback-using-ASP.Net-AsyncFileUpload-Control.aspxhttp://www.aspsnippets.com/Articles/Display-image-after-upload-without-page-refresh-or-postback-using-ASP.Net-AsyncFileUpload-Control.aspx

    Thank you.

    Monday, July 29, 2013 6:04 AM
  • User-821857111 posted

    You can use this jQuery plugin to upload images via AJAX: http://malsup.com/jquery/form/#file-upload

    Monday, July 29, 2013 8:08 AM
  • User-821857111 posted

    How to add ajax toolkit?

    You can't use these controls in ASP.NET Web Pages.

    Monday, July 29, 2013 8:09 AM
  • User895691971 posted

    As notified by Mike, Web Pages don't allow these controls, I should have Web Forms for that! But I don't want them!

    However that jQuery plugin, by Mike! I am going to check that for this work. Will let you know.

    Monday, July 29, 2013 10:23 AM
  • User895691971 posted

    You can use this jQuery plugin to upload images via AJAX: http://malsup.com/jquery/form/#file-upload

    I have read the whole page, but they just provide a tutorial about the form sending, I can send that! But I am not able to send the file, as only the name is that's provided in the input[type="text"] but not the file in the file input field! 

    I need help to send the images, no matter they are uploaded on the current page or other! jQuery or Ajax! Any option..

    Monday, July 29, 2013 10:47 AM
  • User753101303 posted

    So you mean you want to send a file whose name is in an input type="text" rather than selected by an input type="file" ?

    Generally speaking it can't be done for safety reason, the user have to explicitely tell which files he want to download to the server. You may want to give a broader overview. Can you confirm that this is not the user that should select this file ?!

    If you do use an input type="file" this is also where ajax starts. Basically if the browser supports the needed features you are able to get at the file content of the selected file that you can now send using AJAX (so this is not because you see the same user interface than for a non AJAX posted file that you can't do it using AJAX)...

    Monday, July 29, 2013 11:42 AM
  • User895691971 posted

    Ohoo, NO!

    I want to send the whole file. Want to upload the file, not just its name!

    I am using ajax as I want to send the data without loading the whole page (without using IsPost, and post). So when I tried to upload the photo, no photo was found! As the photo was not sent to the next page.

    Thats why I wanted help, to get the photo on the ajax page! To be uploaded and to be saved.

    Monday, July 29, 2013 12:14 PM
  • User753101303 posted

    Well this is not what I asked. You are talking about an input type="text" control even though it seems to me that the  http://malsup.com/jquery/form/#file-upload sample uses an input type="file" control.

    So my understanding was that perhaps you tried to tell that you do want an input type="text" that would hold the file name and that you would like to upload the content of this file ???

    So could you confirm that using an input type="file" control is what you expect ? If yes, try to explain again the problem you seems to have with this tutorial ? Another option would be to do it yourself to better understand how it works.

    By the way, do you have something that works with the usual post approach. Note that than not all browsers can use Ajax to perform file uploads (even though a browser support Ajax, it may not support the "File API" (http://www.w3.org/TR/FileAPI/ ) needed to get at the file content so that it can then be then sent to the server using Ajax...

     

    Monday, July 29, 2013 12:32 PM
  • User895691971 posted

    What O.o ?

    Dude, I said I have a form like this

    <form>
    <input type="text" />
    <input type="file" />
    <input type="submit" />
    </form>

    I am not using other properties, as this was just to tell you that I am having a file input, as well as a text input. If I send only the text information it gets saved! But when I send the image file too, it doesn't. 

    Monday, July 29, 2013 12:45 PM
  • User-821857111 posted

    To upload files, your form needs an enctype of multipart/form-data, and it needs an action pointing to the "new" page, and it needs to have its method set to POST (GET is the default if no method is specified). Here is a sample based on the demo at the site I linked to:

    AjaxfileUpload.cshtml:

    @{
        
    }
    
    <!DOCTYPE html>
    
    <html lang="en">
        <head>
            <meta charset="utf-8" />
            <title></title>
            <style>
                body { padding: 30px }
                form { display: block; margin: 20px 0; background: #eee; border-radius: 10px; padding: 15px; width: 370px; }
                .progress { ; width:400px; border: 1px solid #ddd; padding: 1px; border-radius: 3px; }
                .bar { background-color: #B4F5B4; width:0%; height:20px; border-radius: 3px; }
                .percent { ; display:inline-block; top:3px; left:48%; }
            </style>
            <script type="text/javascript" src="/Scripts/jquery-1.8.3.min.js"></script>
            <script src="/Scripts/jquery.form.min.js"></script>
    <script>
        $(function () {
            var bar = $('.bar');
            var percent = $('.percent');
            var status = $('#status');
    
            $('form').ajaxForm({
                beforeSend: function () {
                    status.empty();
                    var percentVal = '0%';
                    bar.width(percentVal)
                    percent.html(percentVal);
                },
                uploadProgress: function (event, position, total, percentComplete) {
                    var percentVal = percentComplete + '%';
                    bar.width(percentVal)
                    percent.html(percentVal);
                },
                success: function () {
                    var percentVal = '100%';
                    bar.width(percentVal)
                    percent.html(percentVal);
                },
                complete: function (xhr) {
                    status.html(xhr.responseText.trim());
                }
            });
        });
    
    </script>
        </head>
        <body>
            <h1>File Upload Progress Demo @DateTime.Now</h1>
    	
    	<form action="AjaxFileUpload2/" method="post" enctype="multipart/form-data">
                <input type="file" name="myfile"><br>
                <input type="submit" value="Upload File to Server">
            </form>
        
            <div class="progress">
                <div class="bar"></div >
                <div class="percent">0%</div >
            </div>
        
            <div id="status"></div>
        </body>
    </html>
    


    AjaxfileUpload2.cshtml:

    @{
        var filename = "nothing";
        try{
            if(Request.Files.Count > 0){
                filename = Request.Files[0].FileName;
            }
        }
        catch(HttpException ex){
            filename = "Upload too large";
        }
    }
    @filename



    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, July 29, 2013 3:09 PM
  • User895691971 posted

    Sir, can I get the link to this jQuery ajax thing? I mean some tutorial or something like from where I can get knowledge of it, as its my first time to even look at it, till now I was using that old Ajax method!

    Would appreciate, however I do have enctype set to multipart/form-data but no action!

    Monday, July 29, 2013 3:13 PM
  • User-821857111 posted

    You can get jquery from here: http://jquery.com

    You can get the form plugin from the link I posted in the other reply.

    till now I was using that old Ajax method!

    As I pointed out a few weeks ago, no one does that anymore.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, July 29, 2013 4:59 PM
  • User379720387 posted

    I am using WebPages.

    Is this an alternative for what I am doing now?  I.e. a post back then requesting variables and writing them to tables?

    Monday, July 29, 2013 5:21 PM
  • User895691971 posted

    You can get jquery from here: http://jquery.com

    You can get the form plugin from the link I posted in the other reply.

    Afzaal.Ahmad.Zeeshan

    till now I was using that old Ajax method!

    As I pointed out a few weeks ago, no one does that anymore.

    Will work it out! Thanks Mike, as always :)

    Tuesday, July 30, 2013 2:25 AM
  • User895691971 posted

    AjaxfileUpload2.cshtml:

    filename = Request.Files[0].FileName; 

    Hi, Mike you redirected me here from my other post!

    Ok, one confusion, why is that 0 in with files? Is that some kind of parameter or something?

    [qoute user="wavemaster"]

    Is this an alternative for what I am doing now?  I.e. a post back then requesting variables and writing them to tables?

    [/qoute]

    What do you mean? 

    Tuesday, July 30, 2013 2:31 AM
  • User753101303 posted

    It just reads the first posted file from the list of posted files. You may want first to check Request.Files.Length in case the user doesn't have selected any file...

    "post back then requesting variables and writing them to tables" : this is exactly what you'll do with Ajax (use request["myField"]).

    A part of the confusion seems to be that you consider that an Ajax and a regular POST requests are very different. An ajax request is "just" a request that is done "from within" the client side page without replacing it while a regular post is done by the browser and the result (at least in most cases) is intended to replace entirely the current page. Other than that the requests are very similar up to the point that the same code server side handling should work for both cases.

    Make sure also you have a name attribute on your input fields (input fields without a name attribute are not posted to the server).

    To better narrow down at which step you are, you could try :
    - to create a simple form as the one you shown previously
    - handle the post using a regular POST method as done usually
    - then add the ajaxForm call to make it an AJAX call and see how it behaves

    You lkkely have very only very small thing to change to make it work. Double check also you do need an Ajax call ? This is report progress during the file upload ?

     

     

    Tuesday, July 30, 2013 5:09 AM
  • User895691971 posted

    Yes, I was pretty confused about it, however what if I have many files? Ok, then must loop it! But how?

    And pretty clear information about ajax and post. Thanks! :)

    Tuesday, July 30, 2013 5:30 AM
  • User753101303 posted

    You could try something such as http://www.west-wind.com/weblog/posts/2012/Mar/06/Using-the-HTML5-input-typefile-multiplemultiple-Tag-in-ASPNET :

    for (int i = 0; i < Request.Files.Count; i++) {     HttpPostedFileBase file = Request.Files[i];  etc...

    (it just loops on the Request.Files collection). Note that for this to happen, the input type="file" tag uses the multiple="multiple" attribute (and the browser must support it). Another option is to show multiple input type="file" tags...

     

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Tuesday, July 30, 2013 7:08 AM