AJAX and uploading files ?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • wmgilligan
    Developer Partner




    • Feb 2006
    • 742

    #1

    AJAX and uploading files ?

    Has anyone successfully gotten AJAX to work with the mivascript functions for receiving an image?

    I am working on a project where I need to use ajax (xhr) to upload.

    The code is pretty straightforward:
    Code:
       xhr.setRequestHeader("enctype", "multipart/form-data");
       xhr.setRequestHeader("Content-Type", "image/jpeg");
       xhr.open('POST','https://thesite.com/uptest.mvc');
       xhr.send({file: filevar, name: 'thename');
    But it simply fails.
    I have verified the paths, the uptest is responding, but its like the image itself just doesn't get passed.
    Is it even possible?

    FYI: the uptest.mvc contains the standard miva upload functions Miva_ValidateFileUpload and Miva_ProcessFileUpload" but the validation never happens.
    William Gilligan - Orange Marmalade, Inc.
    www.OrangeMarmaladeinc.com
  • Bruce - PhosphorMedia
    Developer Partner











    • Mar 2006
    • 11256

    #2
    Re: AJAX and uploading files ?

    Just wanted you to know *I'm* not ignoring you...i just don't really have a clue atm.
    Bruce Golub
    Phosphor Media - "Your Success is our Business"

    Improve Your Customer Service | Get MORE Customers | Edit CSS/Javascript/HTML Easily | Make Your Site Faster | Get Indexed by Google | Free Modules | Follow Us on Facebook
    phosphormedia.com

    Comment

    • wmgilligan
      Developer Partner




      • Feb 2006
      • 742

      #3
      Re: AJAX and uploading files ?

      Originally posted by Bruce - PhosphorMedia View Post
      Just wanted you to know *I'm* not ignoring you...i just don't really have a clue atm.
      Hey Bruce,
      Thanks. Its good to know.

      For the time being I had to - for the first time ever - switch to using PHP (for the receiving end).
      I just had to stop - I don't have a lot of hair left - and pulling out more is not good...
      In the past, I was always able to get mivascript to do anything I needed.

      The reason I "must" use the ajax method is because this is an iOS app for the iPhone / iPad, etc.
      The receiving end is all Miva - except this one file. I hope to change that if possible.
      William Gilligan - Orange Marmalade, Inc.
      www.OrangeMarmaladeinc.com

      Comment

      • Bruce - PhosphorMedia
        Developer Partner











        • Mar 2006
        • 11256

        #4
        Re: AJAX and uploading files ?

        Understand. I know Gordon's been playing a lot with Ajax, but hasn't done much with the upload functions in mivascript. my guess the main issue is linking the two, since the upload process has a some dark corners in it<g>.
        Bruce Golub
        Phosphor Media - "Your Success is our Business"

        Improve Your Customer Service | Get MORE Customers | Edit CSS/Javascript/HTML Easily | Make Your Site Faster | Get Indexed by Google | Free Modules | Follow Us on Facebook
        phosphormedia.com

        Comment

        • Emma
          Mivite

          • Mar 2006
          • 230

          #5
          Re: AJAX and uploading files ?

          Hi,

          After testing this script, everything worked fine:

          HTML file: "test.html"


          PHP Code:
          <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
          <html>
          <head><title>Test</title></head>
          
          <body>
          <form id="file-form" action="http://mydomain.com/upload.mvc" method="POST">
          <input type="file" id="file-select" name="photos[]" multiple/>
          <button type="submit" id="upload-button">Upload</button>
          </form>
          <progress></progress>
          <script>
          var form             = document.getElementById('file-form');
          var fileSelect         = document.getElementById('file-select');
          var uploadButton     = document.getElementById('upload-button');
          form.onsubmit = function(event) {event.preventDefault();// Update button text.
          uploadButton.innerHTML = 'Uploading...';
          
          // Get the selected files from the input.
          var files = fileSelect.files;
          
          // Create a new FormData object.
          var formData = new FormData();
          
          // Loop through each of the selected files.
          for (var i = 0; i < files.length; i++) {var file = files[i];
           // Check the file type.
          if (!file.type.match('image.*')) {continue;}
          
          // Add the file to the request.
          formData.append('photos[]', file, file.name);}
          // Set up the request.
          var xhr = new XMLHttpRequest();
          
          // Open the connection. !!! change the domain & path !!!
          xhr.open('POST', 'http://mydomain.com/upload.mvc', true);
          // Set up a handler for when the request finishes.
          
          xhr.onload = function () {if (xhr.status === 200) {// File(s) uploaded.
          uploadButton.innerHTML = 'Upload';} else {alert('An error occurred!');}};
          
          // Send the Data.
          xhr.send(formData);}
          </script></body>
          </html> 
          


          --- And a "regular" uplaod.mvc script:

          HTML Code:
          
          <MvFUNCTION NAME="Miva_ValidateFileUpload" PARAMETERS="field, filename, content_type" standardoutputlevel="compresswhitespace">	<miva standardoutputlevel="compresswhitespace">		<mvassign name="g.sid" value="{makesessionid()}">		<mvassign name="g.ftempf" 			value="{'/test/upload/'$g.sid}">		<mvassign name="l.existafld" 		value="{sexists(g.ftempf)}">		<mvif expr="{NOT l.existafld}">				<mvassign name="l.k" 			value="{smkdir(g.ftempf)}">		<mvassign name="l.k" 			value="{schmod(g.ftempf, 493)}">	</mvif>			<mvcomment>Alowed size</mvcomment>	<mvassign name="l.maxi_size" 		value="10000000">	<mvassign name="l.ret" 				value="-1">	<mvassign name="l.notok" 			value="1">		<mvcomment>Alowed content types</mvcomment>	<mvassign name="l.content_types" 	value="{'gif|jpg|jpeg|png'}">	<mvassign name="l.no_points" 		value="{(len(l.filename)-len(glosub(l.filename,'.','')))+1}">	<mvassign name="l.extension" 		value="{gettoken(l.filename,'.',l.no_points)}">		<mvassign name="l.no_types" 		value="{(len(l.content_types)-len(glosub(l.content_types,'|','')))+1}">	<MvWHILE EXPR="{ l.cnt LT l.no_types }">		<mvassign name="l.cnt" 			value="{l.cnt+1}">		<MvIF EXPR="{ tolower(l.extension) EQ gettoken(l.content_types,'|',l.cnt) }">			<mvassign name="l.notok" 	value="0">			<mvassign name="l.ret" 		value="{l.maxi_size}">		</MvIF>	</MvWHILE>		<MvIF EXPR="{ l.notok }">		<MvEVAL EXPR="{'not ok'}">	</MvIF>	<MvFUNCRETURN value="{l.ret}"></MvFUNCTION>
          
          
          <MvFUNCTION NAME="Miva_ProcessFileUpload" PARAMETERS="field,filename,status,tempfile,content_type,size" standardoutputlevel="compresswhitespace">
          	<mvcomment><mveval expr="{silentdebug(l.status,'Miva_ProcessFileUpload - status')}">	<mveval expr="{silentdebug(l.tempfile,'Miva_ProcessFileUpload - tempfile')}"></mvcomment>		<mvassign name="l.nfilename" 		value="{s.dyn_time_t$'_'$makesessionid()}">		<mvassign name="l.no_points" 		value="{(len(l.filename)-len(glosub(l.filename,'.','')))+1}">	<mvassign name="l.extension" 		value="{gettoken(l.filename,'.',l.no_points)}">	<mvassign NAME="l.newfilename"		value="{ l.nfilename$'.'$l.extension }">	<mvassign NAME="l.dir"				value="{ '/test/upload/'$g.sid$'/' }">		<mvassign NAME = "l.filepath"		value = "{ l.dir $ l.newfilename }">		<mvassign name="l.save_it" 			value="{fscopy(l.tempfile,l.filepath)}">	<mvassign name="l.ok" 				value="{schmod(l.filepath, 511)}">
          	<MvIF EXPR="{ l.status EQ 'SKIPPED' }">		<mvassign name="l.error" value="{'Fichier non autoris&eacute;'}">	<MvElseIF EXPR="{ l.status EQ 'COMPLETE' }">		<mvassign name="l.re" value="Fichier envoyé avec succ&egrave;s!">		<mvcomment><mvassign name="l.ok" value="{Post_Traitement(l.filepath,l.newfilename,l.dir,l.destdir)}"></mvcomment>				<mvif expr="{'Corrupt JPEG' CIN l.ok }">			<mvassign name="l.filepath" value="">			<mvassign name="l.error" value="{'Fichier corrompu. Merci de choisir un autre fichier !'}">			<mvassign name="l.mesg" value="{'Fichier corrompu. Merci de choisir un autre fichier !'}">		<mvelseif expr="{ 'is not a valid JPEG' CIN l.ok }">			<mvassign name="l.filepath" value="">			<mvassign name="l.error" value="{'Fichier corrompu. Merci de choisir un autre fichier !'}">			<mvassign name="l.mesg" value="{'Fichier corrompu. Merci de choisir un autre fichier !'}">		<mvelseif expr="{l.ok EQ ''}">			<mvassign name="l.error" value="">			<mvassign name="l.mesg" value="">		<mvelse>			<mvassign name="l.error" value="">			<mvassign name="l.mesg" value="">		</mvif>			<MvElseIF EXPR="{ l.status EQ 'PARTIAL' }">		<mvassign name="l.error" value="{'Le fichier semble être corrompu et il n\'a pas été envoyé.\\n Merci de réesayer ou de changer le ficher à transmettre'}">	</MvIF>
          	<mvif expr="{l.error}">		<mvassign name="l.re" value="{l.error}">	</mvif>		<mveval expr="{l.re}"></MvFUNCTION>
          PS: Sorry, I tried to format this code even manually on the board and it won't show up correctly :( . Also, the folder I created to test on my server was /test/upload/ ... just for info ...

          Best regards,
          Emma
          Last edited by Emma; 05-05-14, 05:57 AM.
          Zen Radio : Relax :) : www.zenradio.fm
          MivaScript Tutorials & Scripts : www.mivascript.org

          Comment

          • burch
            Administrator

            • Mar 2009
            • 630

            #6
            Re: AJAX and uploading files ?

            MivaScript's file upload mechanism only works with multipart/form-data submissions. Despite setting the enctype header in your code sample, your code is submitting the image directly with a content-type of image/jpeg.

            If you're using the 5.19 engine you could handle this with the new unknown content-type mechanism and s.content_data, but you could also just change your JS code to use FormData like Emma's example above, which will ensure that the request is sent as a multipart mime message.

            Here's a modified version of your example that uses FormData:

            Code:
            <script language="JavaScript">
            function go()
            {
                var filevar = document.getElementById( 'file' );
                var xhr = new XMLHttpRequest();
                var formdata = new FormData();
            
                formdata.append( 'file', filevar.files[ 0 ] );
                formdata.append( 'name', 'thename' );
                xhr.open('POST','http://localhost/~burch/uptest.mvc');
                xhr.send( formdata );
            }
            </script>
            
            <form>
            <input type="file" name="file" id="file">
            <input type="button" onclick="go()">
            </form>

            Comment

            • wmgilligan
              Developer Partner




              • Feb 2006
              • 742

              #7
              Re: AJAX and uploading files ?

              Sweet!
              I will let you know how it goes when I swing back to it - soon!
              William Gilligan - Orange Marmalade, Inc.
              www.OrangeMarmaladeinc.com

              Comment

              • wmgilligan
                Developer Partner




                • Feb 2006
                • 742

                #8
                Re: AJAX and uploading files ?

                OK - this was way to easy in the end.
                Burch - thanks for saying just the right thing.
                All that I needed to do was remove my content-type header, and all is good!

                For the record - this code functions inside an iPhone app, which does not use <form> tags or submit buttons as html / web coders know them (this app does not use a web view).

                hmmm... am I making the first iPhone app that uses mivascript as its backend?
                William Gilligan - Orange Marmalade, Inc.
                www.OrangeMarmaladeinc.com

                Comment

                Working...
                X