Rectangle 27 2

I ended up doing it like this. This reads all the files that are selected with file dialog. I don't need to send these to node.js. I can just manipulate these on client.

<input type='file' accept='text/plain' multiple (change)='openFile($event)'>

openFile(event) {
    let input = event.target;
    for (var index = 0; index < input.files.length; index++) {
        let reader = new FileReader();
        reader.onload = () => {
            // this 'text' is the content of the file
            var text = reader.result;
        }
        reader.readAsText(input.files[index]);
    };
}

It is very basic example of how you can do it.

javascript - Upload and read file client side, with angular 2 - Stack ...

javascript angular typescript client-side
Rectangle 27 47

I just developed a javascript library called JIC to solve that problem. It allows you to compress jpg and png on the client side 100% with javascript and no external libraries required!

@brunobar79 Can this export the image to a JavaScript Blob, so that we can upload it without the use of PHP?

@Elegant.Scripting You're uploading binary data, PHP is not a requirement at all but you will need some server side language to handle file uploads.

the image i am trying to compress using JIC is only make the size larger. has this happened to anyone else?

javascript - Compress images on client side before uploading - Stack O...

javascript jquery jquery-plugins
Rectangle 27 9

You might be able to resize the image with canvas and export it using dataURI. Not sure about compression, though.

javascript - Compress images on client side before uploading - Stack O...

javascript jquery jquery-plugins
Rectangle 27 4

I'm late to the party, but this solution worked for me quite well. Based on this library, you can use a function lik this - setting the image, quality, max-width, and output format (jepg,png):

function compress(source_img_obj, quality, maxWidth, output_format){
    var mime_type = "image/jpeg";
    if(typeof output_format !== "undefined" && output_format=="png"){
        mime_type = "image/png";
    }

    maxWidth = maxWidth || 1000;
    var natW = source_img_obj.naturalWidth;
    var natH = source_img_obj.naturalHeight;
    var ratio = natH / natW;
    if (natW > maxWidth) {
        natW = maxWidth;
        natH = ratio * maxWidth;
    }

    var cvs = document.createElement('canvas');
    cvs.width = natW;
    cvs.height = natH;

    var ctx = cvs.getContext("2d").drawImage(source_img_obj, 0, 0, natW, natH);
    var newImageData = cvs.toDataURL(mime_type, quality/100);
    var result_image_obj = new Image();
    result_image_obj.src = newImageData;
    return result_image_obj;
}

Sorry to break the new to you, but brunobar79's solution is faster and better.

That's the beauty of stack overflow :)

javascript - Compress images on client side before uploading - Stack O...

javascript jquery jquery-plugins
Rectangle 27 4

The theory is that you can use canvas to resize the images on the client before uploading. The prototype example seems to work only in recent browsers, interesting idea though...

However, Im not sure about using canvas to compress images, but you can certainly resize them.

by the i need something like smushit.com

I dont think you can replicate Smushit on the client side.

javascript - Compress images on client side before uploading - Stack O...

javascript jquery jquery-plugins
Rectangle 27 1

I think a post would be the better way to do this. Dealing with escaped data is a much easier, more established problem then in-memory files and pushing files to the server with client side javascript. Moreover, escaping data is done for a reason. What you're trying to do is going to welcome a lot of security vulnerabilities.

var data = "...";// this is your data that you want to pass to the server (could be json)
//next you would initiate a XMLHTTPRequest as following (could be more advanced):
var url = "get_data.php";//your url to the server side file that will receive the data.
http.open("POST", url, true);

//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");

http.onreadystatechange = function() {//Call a function when the state changes.
    if(http.readyState == 4 && http.status == 200) {
        alert(http.responseText);//check if the data was revived successfully.
    }
}
http.send(data);

Thanks for your reply. It gave me the hints I needed to find the solution on my own. I haven't implemented it yet, other things came in the way, but once I do, I'll post the solution here. Once again, thanks for the hints that put me on the right track.

How to create an in memory file and upload to server using client side...

javascript file-upload
Rectangle 27 1

I think a post would be the better way to do this. Dealing with escaped data is a much easier, more established problem then in-memory files and pushing files to the server with client side javascript. Moreover, escaping data is done for a reason. What you're trying to do is going to welcome a lot of security vulnerabilities.

var data = "...";// this is your data that you want to pass to the server (could be json)
//next you would initiate a XMLHTTPRequest as following (could be more advanced):
var url = "get_data.php";//your url to the server side file that will receive the data.
http.open("POST", url, true);

//Send the proper header information along with the request
http.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
http.setRequestHeader("Content-length", params.length);
http.setRequestHeader("Connection", "close");

http.onreadystatechange = function() {//Call a function when the state changes.
    if(http.readyState == 4 && http.status == 200) {
        alert(http.responseText);//check if the data was revived successfully.
    }
}
http.send(data);

Thanks for your reply. It gave me the hints I needed to find the solution on my own. I haven't implemented it yet, other things came in the way, but once I do, I'll post the solution here. Once again, thanks for the hints that put me on the right track.

How to create an in memory file and upload to server using client side...

javascript file-upload
Rectangle 27 3

If you are looking for a library to carry out client-side image compression, you can check this out:compress.js. This will basically help you compress multiple images purely with JavaScript and convert them to base64 string. You can optionally set the maximum size in MB and also the preferred image quality.

Sorry to break the new to you, but brunobar79's solution is faster and better.

javascript - Compress images on client side before uploading - Stack O...

javascript jquery jquery-plugins
Rectangle 27 5

Following is a solution that strongly protects files.

  • An attacker can access the server but won't be able to use the data.
  • If user loses its password, data is lost too.
  • Even you (the developer) cannot access the data (This means you cannot help the user if he encounters any problems).

If its what you need, go for it ^^. Note: all that follows happens on the Server side.

  • use https for all transmissions
  • When the user log in, create a hash of the user's password (e.g. sha(password + salt))
  • Store the hash in the user's session
  • When an upload is done, use symmetric encryption (e.g. AES) to encipher the data with the hash stored in the session as the key.
  • When a download is done, use the same symmetric decryption method to decipher the file and send it back to the user.

This means that only a logged user can access the data as plain. And only the user to whom the data belongs. The only possibility to access the user's data is to know his password.

Note: if the user that uploads the file and the one that read the file are not the same person, you can use a combination of asymmetric and symmetric encryption instead:

  • generate a public/private key pair for the recipient.
  • (symmetric) encrypt the private key with the recipient's hash or a dependency of his password.

(new) Asymmetric encryption appear to be much slower than symmetric encryption (10-100x depending on algorithms/architecture). Hence it is far better to generate a random number (the session key), asymmetric-encrypt twice (once with sender's public key, once with recipient's public key) it and store them. Then use symmetric encryption to encrypt the file (use the plain session key as the symmetric key).

a) decipher his private key with his hash or password dependency.

b) (new) Use private key to decipher the recipient's encrypted session key. Then use symmetric decryption to decipher the file.

Client side (javascript) file upload encryption - Stack Overflow

javascript encryption file-upload
Rectangle 27 5

Following is a solution that strongly protects files.

  • An attacker can access the server but won't be able to use the data.
  • If user loses its password, data is lost too.
  • Even you (the developer) cannot access the data (This means you cannot help the user if he encounters any problems).

If its what you need, go for it ^^. Note: all that follows happens on the Server side.

  • use https for all transmissions
  • When the user log in, create a hash of the user's password (e.g. sha(password + salt))
  • Store the hash in the user's session
  • When an upload is done, use symmetric encryption (e.g. AES) to encipher the data with the hash stored in the session as the key.
  • When a download is done, use the same symmetric decryption method to decipher the file and send it back to the user.

This means that only a logged user can access the data as plain. And only the user to whom the data belongs. The only possibility to access the user's data is to know his password.

Note: if the user that uploads the file and the one that read the file are not the same person, you can use a combination of asymmetric and symmetric encryption instead:

  • generate a public/private key pair for the recipient.
  • (symmetric) encrypt the private key with the recipient's hash or a dependency of his password.

(new) Asymmetric encryption appear to be much slower than symmetric encryption (10-100x depending on algorithms/architecture). Hence it is far better to generate a random number (the session key), asymmetric-encrypt twice (once with sender's public key, once with recipient's public key) it and store them. Then use symmetric encryption to encrypt the file (use the plain session key as the symmetric key).

a) decipher his private key with his hash or password dependency.

b) (new) Use private key to decipher the recipient's encrypted session key. Then use symmetric decryption to decipher the file.

Client side (javascript) file upload encryption - Stack Overflow

javascript encryption file-upload
Rectangle 27 124

Ajax post and upload file is possible. I'm using jQuery $.ajax function to load my files. I tried to use the XHR object but could not get results on the server side with PHP.

As you can see, you must create a FormData object, empty or from (serialized? - $('#yourForm').serialize()) existing form, and then attach the input file.

For the PHP process you can use something like this:

//print_r($_FILES);
$fileName = $_FILES['file']['name'];
$fileType = $_FILES['file']['type'];
$fileError = $_FILES['file']['error'];
$fileContent = file_get_contents($_FILES['file']['tmp_name']);

if($fileError == UPLOAD_ERR_OK){
   //Processes your file here
}else{
   switch($fileError){
     case UPLOAD_ERR_INI_SIZE:   
          $message = 'Error al intentar subir un archivo que excede el tamao permitido.';
          break;
     case UPLOAD_ERR_FORM_SIZE:  
          $message = 'Error al intentar subir un archivo que excede el tamao permitido.';
          break;
     case UPLOAD_ERR_PARTIAL:    
          $message = 'Error: no termin la accin de subir el archivo.';
          break;
     case UPLOAD_ERR_NO_FILE:    
          $message = 'Error: ningn archivo fue subido.';
          break;
     case UPLOAD_ERR_NO_TMP_DIR: 
          $message = 'Error: servidor no configurado para carga de archivos.';
          break;
     case UPLOAD_ERR_CANT_WRITE: 
          $message= 'Error: posible falla al grabar el archivo.';
          break;
     case  UPLOAD_ERR_EXTENSION: 
          $message = 'Error: carga de archivo no completada.';
          break;
     default: $message = 'Error: carga de archivo no completada.';
              break;
    }
      echo json_encode(array(
               'error' => true,
               'message' => $message
            ));
}
formData.append('file', $('#file')[0].files[0]);
undefined
console.log(formData)
_proto_

This should be the accepted answer.

Not supported by IE 9, in case some is stuck in the same hell as I

var formData = new FormData();     formData.append('file', document.getElementById('file').files[0]);     $.ajax({            url : $("form[name='uploadPhoto']").attr("action"),            type : 'POST',            data : formData,            processData: false,  // tell jQuery not to process the data            contentType: false,  // tell jQuery not to set contentType            success : function(data) {                console.log(data);                alert(data);            }     });

javascript - jQuery Ajax File Upload - Stack Overflow

javascript jquery ajax post file-upload
Rectangle 27 123

Ajax post and upload file is possible. I'm using jQuery $.ajax function to load my files. I tried to use the XHR object but could not get results on the server side with PHP.

As you can see, you must create a FormData object, empty or from (serialized? - $('#yourForm').serialize()) existing form, and then attach the input file.

For the PHP process you can use something like this:

//print_r($_FILES);
$fileName = $_FILES['file']['name'];
$fileType = $_FILES['file']['type'];
$fileError = $_FILES['file']['error'];
$fileContent = file_get_contents($_FILES['file']['tmp_name']);

if($fileError == UPLOAD_ERR_OK){
   //Processes your file here
}else{
   switch($fileError){
     case UPLOAD_ERR_INI_SIZE:   
          $message = 'Error al intentar subir un archivo que excede el tamao permitido.';
          break;
     case UPLOAD_ERR_FORM_SIZE:  
          $message = 'Error al intentar subir un archivo que excede el tamao permitido.';
          break;
     case UPLOAD_ERR_PARTIAL:    
          $message = 'Error: no termin la accin de subir el archivo.';
          break;
     case UPLOAD_ERR_NO_FILE:    
          $message = 'Error: ningn archivo fue subido.';
          break;
     case UPLOAD_ERR_NO_TMP_DIR: 
          $message = 'Error: servidor no configurado para carga de archivos.';
          break;
     case UPLOAD_ERR_CANT_WRITE: 
          $message= 'Error: posible falla al grabar el archivo.';
          break;
     case  UPLOAD_ERR_EXTENSION: 
          $message = 'Error: carga de archivo no completada.';
          break;
     default: $message = 'Error: carga de archivo no completada.';
              break;
    }
      echo json_encode(array(
               'error' => true,
               'message' => $message
            ));
}
formData.append('file', $('#file')[0].files[0]);
undefined
console.log(formData)
_proto_

This should be the accepted answer.

Not supported by IE 9, in case some is stuck in the same hell as I

var formData = new FormData();     formData.append('file', document.getElementById('file').files[0]);     $.ajax({            url : $("form[name='uploadPhoto']").attr("action"),            type : 'POST',            data : formData,            processData: false,  // tell jQuery not to process the data            contentType: false,  // tell jQuery not to set contentType            success : function(data) {                console.log(data);                alert(data);            }     });

javascript - jQuery Ajax File Upload - Stack Overflow

javascript jquery ajax post file-upload
Rectangle 27 123

Ajax post and upload file is possible. I'm using jQuery $.ajax function to load my files. I tried to use the XHR object but could not get results on the server side with PHP.

As you can see, you must create a FormData object, empty or from (serialized? - $('#yourForm').serialize()) existing form, and then attach the input file.

For the PHP process you can use something like this:

//print_r($_FILES);
$fileName = $_FILES['file']['name'];
$fileType = $_FILES['file']['type'];
$fileError = $_FILES['file']['error'];
$fileContent = file_get_contents($_FILES['file']['tmp_name']);

if($fileError == UPLOAD_ERR_OK){
   //Processes your file here
}else{
   switch($fileError){
     case UPLOAD_ERR_INI_SIZE:   
          $message = 'Error al intentar subir un archivo que excede el tamao permitido.';
          break;
     case UPLOAD_ERR_FORM_SIZE:  
          $message = 'Error al intentar subir un archivo que excede el tamao permitido.';
          break;
     case UPLOAD_ERR_PARTIAL:    
          $message = 'Error: no termin la accin de subir el archivo.';
          break;
     case UPLOAD_ERR_NO_FILE:    
          $message = 'Error: ningn archivo fue subido.';
          break;
     case UPLOAD_ERR_NO_TMP_DIR: 
          $message = 'Error: servidor no configurado para carga de archivos.';
          break;
     case UPLOAD_ERR_CANT_WRITE: 
          $message= 'Error: posible falla al grabar el archivo.';
          break;
     case  UPLOAD_ERR_EXTENSION: 
          $message = 'Error: carga de archivo no completada.';
          break;
     default: $message = 'Error: carga de archivo no completada.';
              break;
    }
      echo json_encode(array(
               'error' => true,
               'message' => $message
            ));
}
formData.append('file', $('#file')[0].files[0]);
undefined
console.log(formData)
_proto_

This should be the accepted answer.

Not supported by IE 9, in case some is stuck in the same hell as I

var formData = new FormData();     formData.append('file', document.getElementById('file').files[0]);     $.ajax({            url : $("form[name='uploadPhoto']").attr("action"),            type : 'POST',            data : formData,            processData: false,  // tell jQuery not to process the data            contentType: false,  // tell jQuery not to set contentType            success : function(data) {                console.log(data);                alert(data);            }     });

javascript - jQuery Ajax File Upload - Stack Overflow

javascript jquery ajax post file-upload
Rectangle 27 123

Ajax post and upload file is possible. I'm using jQuery $.ajax function to load my files. I tried to use the XHR object but could not get results on the server side with PHP.

As you can see, you must create a FormData object, empty or from (serialized? - $('#yourForm').serialize()) existing form, and then attach the input file.

For the PHP process you can use something like this:

//print_r($_FILES);
$fileName = $_FILES['file']['name'];
$fileType = $_FILES['file']['type'];
$fileError = $_FILES['file']['error'];
$fileContent = file_get_contents($_FILES['file']['tmp_name']);

if($fileError == UPLOAD_ERR_OK){
   //Processes your file here
}else{
   switch($fileError){
     case UPLOAD_ERR_INI_SIZE:   
          $message = 'Error al intentar subir un archivo que excede el tamao permitido.';
          break;
     case UPLOAD_ERR_FORM_SIZE:  
          $message = 'Error al intentar subir un archivo que excede el tamao permitido.';
          break;
     case UPLOAD_ERR_PARTIAL:    
          $message = 'Error: no termin la accin de subir el archivo.';
          break;
     case UPLOAD_ERR_NO_FILE:    
          $message = 'Error: ningn archivo fue subido.';
          break;
     case UPLOAD_ERR_NO_TMP_DIR: 
          $message = 'Error: servidor no configurado para carga de archivos.';
          break;
     case UPLOAD_ERR_CANT_WRITE: 
          $message= 'Error: posible falla al grabar el archivo.';
          break;
     case  UPLOAD_ERR_EXTENSION: 
          $message = 'Error: carga de archivo no completada.';
          break;
     default: $message = 'Error: carga de archivo no completada.';
              break;
    }
      echo json_encode(array(
               'error' => true,
               'message' => $message
            ));
}
formData.append('file', $('#file')[0].files[0]);
undefined
console.log(formData)
_proto_

This should be the accepted answer.

Not supported by IE 9, in case some is stuck in the same hell as I

var formData = new FormData();     formData.append('file', document.getElementById('file').files[0]);     $.ajax({            url : $("form[name='uploadPhoto']").attr("action"),            type : 'POST',            data : formData,            processData: false,  // tell jQuery not to process the data            contentType: false,  // tell jQuery not to set contentType            success : function(data) {                console.log(data);                alert(data);            }     });

javascript - jQuery Ajax File Upload - Stack Overflow

javascript jquery ajax post file-upload
Rectangle 27 121

Ajax post and upload file is possible. I'm using jQuery $.ajax function to load my files. I tried to use the XHR object but could not get results on the server side with PHP.

As you can see, you must create a FormData object, empty or from (serialized? - $('#yourForm').serialize()) existing form, and then attach the input file.

For the PHP process you can use something like this:

//print_r($_FILES);
$fileName = $_FILES['file']['name'];
$fileType = $_FILES['file']['type'];
$fileError = $_FILES['file']['error'];
$fileContent = file_get_contents($_FILES['file']['tmp_name']);

if($fileError == UPLOAD_ERR_OK){
   //Processes your file here
}else{
   switch($fileError){
     case UPLOAD_ERR_INI_SIZE:   
          $message = 'Error al intentar subir un archivo que excede el tamao permitido.';
          break;
     case UPLOAD_ERR_FORM_SIZE:  
          $message = 'Error al intentar subir un archivo que excede el tamao permitido.';
          break;
     case UPLOAD_ERR_PARTIAL:    
          $message = 'Error: no termin la accin de subir el archivo.';
          break;
     case UPLOAD_ERR_NO_FILE:    
          $message = 'Error: ningn archivo fue subido.';
          break;
     case UPLOAD_ERR_NO_TMP_DIR: 
          $message = 'Error: servidor no configurado para carga de archivos.';
          break;
     case UPLOAD_ERR_CANT_WRITE: 
          $message= 'Error: posible falla al grabar el archivo.';
          break;
     case  UPLOAD_ERR_EXTENSION: 
          $message = 'Error: carga de archivo no completada.';
          break;
     default: $message = 'Error: carga de archivo no completada.';
              break;
    }
      echo json_encode(array(
               'error' => true,
               'message' => $message
            ));
}
formData.append('file', $('#file')[0].files[0]);
undefined
console.log(formData)
_proto_

This should be the accepted answer.

Not supported by IE 9, in case some is stuck in the same hell as I

var formData = new FormData();     formData.append('file', document.getElementById('file').files[0]);     $.ajax({            url : $("form[name='uploadPhoto']").attr("action"),            type : 'POST',            data : formData,            processData: false,  // tell jQuery not to process the data            contentType: false,  // tell jQuery not to set contentType            success : function(data) {                console.log(data);                alert(data);            }     });

javascript - jQuery Ajax File Upload - Stack Overflow

javascript jquery ajax post file-upload
Rectangle 27 121

Ajax post and upload file is possible. I'm using jQuery $.ajax function to load my files. I tried to use the XHR object but could not get results on the server side with PHP.

As you can see, you must create a FormData object, empty or from (serialized? - $('#yourForm').serialize()) existing form, and then attach the input file.

For the PHP process you can use something like this:

//print_r($_FILES);
$fileName = $_FILES['file']['name'];
$fileType = $_FILES['file']['type'];
$fileError = $_FILES['file']['error'];
$fileContent = file_get_contents($_FILES['file']['tmp_name']);

if($fileError == UPLOAD_ERR_OK){
   //Processes your file here
}else{
   switch($fileError){
     case UPLOAD_ERR_INI_SIZE:   
          $message = 'Error al intentar subir un archivo que excede el tamao permitido.';
          break;
     case UPLOAD_ERR_FORM_SIZE:  
          $message = 'Error al intentar subir un archivo que excede el tamao permitido.';
          break;
     case UPLOAD_ERR_PARTIAL:    
          $message = 'Error: no termin la accin de subir el archivo.';
          break;
     case UPLOAD_ERR_NO_FILE:    
          $message = 'Error: ningn archivo fue subido.';
          break;
     case UPLOAD_ERR_NO_TMP_DIR: 
          $message = 'Error: servidor no configurado para carga de archivos.';
          break;
     case UPLOAD_ERR_CANT_WRITE: 
          $message= 'Error: posible falla al grabar el archivo.';
          break;
     case  UPLOAD_ERR_EXTENSION: 
          $message = 'Error: carga de archivo no completada.';
          break;
     default: $message = 'Error: carga de archivo no completada.';
              break;
    }
      echo json_encode(array(
               'error' => true,
               'message' => $message
            ));
}
formData.append('file', $('#file')[0].files[0]);
undefined
console.log(formData)
_proto_

This should be the accepted answer.

Not supported by IE 9, in case some is stuck in the same hell as I

var formData = new FormData();     formData.append('file', document.getElementById('file').files[0]);     $.ajax({            url : $("form[name='uploadPhoto']").attr("action"),            type : 'POST',            data : formData,            processData: false,  // tell jQuery not to process the data            contentType: false,  // tell jQuery not to set contentType            success : function(data) {                console.log(data);                alert(data);            }     });

javascript - jQuery Ajax File Upload - Stack Overflow

javascript jquery ajax post file-upload
Rectangle 27 121

Ajax post and upload file is possible. I'm using jQuery $.ajax function to load my files. I tried to use the XHR object but could not get results on the server side with PHP.

As you can see, you must create a FormData object, empty or from (serialized? - $('#yourForm').serialize()) existing form, and then attach the input file.

For the PHP process you can use something like this:

//print_r($_FILES);
$fileName = $_FILES['file']['name'];
$fileType = $_FILES['file']['type'];
$fileError = $_FILES['file']['error'];
$fileContent = file_get_contents($_FILES['file']['tmp_name']);

if($fileError == UPLOAD_ERR_OK){
   //Processes your file here
}else{
   switch($fileError){
     case UPLOAD_ERR_INI_SIZE:   
          $message = 'Error al intentar subir un archivo que excede el tamao permitido.';
          break;
     case UPLOAD_ERR_FORM_SIZE:  
          $message = 'Error al intentar subir un archivo que excede el tamao permitido.';
          break;
     case UPLOAD_ERR_PARTIAL:    
          $message = 'Error: no termin la accin de subir el archivo.';
          break;
     case UPLOAD_ERR_NO_FILE:    
          $message = 'Error: ningn archivo fue subido.';
          break;
     case UPLOAD_ERR_NO_TMP_DIR: 
          $message = 'Error: servidor no configurado para carga de archivos.';
          break;
     case UPLOAD_ERR_CANT_WRITE: 
          $message= 'Error: posible falla al grabar el archivo.';
          break;
     case  UPLOAD_ERR_EXTENSION: 
          $message = 'Error: carga de archivo no completada.';
          break;
     default: $message = 'Error: carga de archivo no completada.';
              break;
    }
      echo json_encode(array(
               'error' => true,
               'message' => $message
            ));
}
formData.append('file', $('#file')[0].files[0]);
undefined
console.log(formData)
_proto_

This should be the accepted answer.

Not supported by IE 9, in case some is stuck in the same hell as I

var formData = new FormData();     formData.append('file', document.getElementById('file').files[0]);     $.ajax({            url : $("form[name='uploadPhoto']").attr("action"),            type : 'POST',            data : formData,            processData: false,  // tell jQuery not to process the data            contentType: false,  // tell jQuery not to set contentType            success : function(data) {                console.log(data);                alert(data);            }     });

javascript - jQuery Ajax File Upload - Stack Overflow

javascript jquery ajax post file-upload
Rectangle 27 121

Ajax post and upload file is possible. I'm using jQuery $.ajax function to load my files. I tried to use the XHR object but could not get results on the server side with PHP.

As you can see, you must create a FormData object, empty or from (serialized? - $('#yourForm').serialize()) existing form, and then attach the input file.

For the PHP process you can use something like this:

//print_r($_FILES);
$fileName = $_FILES['file']['name'];
$fileType = $_FILES['file']['type'];
$fileError = $_FILES['file']['error'];
$fileContent = file_get_contents($_FILES['file']['tmp_name']);

if($fileError == UPLOAD_ERR_OK){
   //Processes your file here
}else{
   switch($fileError){
     case UPLOAD_ERR_INI_SIZE:   
          $message = 'Error al intentar subir un archivo que excede el tamao permitido.';
          break;
     case UPLOAD_ERR_FORM_SIZE:  
          $message = 'Error al intentar subir un archivo que excede el tamao permitido.';
          break;
     case UPLOAD_ERR_PARTIAL:    
          $message = 'Error: no termin la accin de subir el archivo.';
          break;
     case UPLOAD_ERR_NO_FILE:    
          $message = 'Error: ningn archivo fue subido.';
          break;
     case UPLOAD_ERR_NO_TMP_DIR: 
          $message = 'Error: servidor no configurado para carga de archivos.';
          break;
     case UPLOAD_ERR_CANT_WRITE: 
          $message= 'Error: posible falla al grabar el archivo.';
          break;
     case  UPLOAD_ERR_EXTENSION: 
          $message = 'Error: carga de archivo no completada.';
          break;
     default: $message = 'Error: carga de archivo no completada.';
              break;
    }
      echo json_encode(array(
               'error' => true,
               'message' => $message
            ));
}
formData.append('file', $('#file')[0].files[0]);
undefined
console.log(formData)
_proto_

This should be the accepted answer.

Not supported by IE 9, in case some is stuck in the same hell as I

var formData = new FormData();     formData.append('file', document.getElementById('file').files[0]);     $.ajax({            url : $("form[name='uploadPhoto']").attr("action"),            type : 'POST',            data : formData,            processData: false,  // tell jQuery not to process the data            contentType: false,  // tell jQuery not to set contentType            success : function(data) {                console.log(data);                alert(data);            }     });

javascript - jQuery Ajax File Upload - Stack Overflow

javascript jquery ajax post file-upload
Rectangle 27 121

Ajax post and upload file is possible. I'm using jQuery $.ajax function to load my files. I tried to use the XHR object but could not get results on the server side with PHP.

As you can see, you must create a FormData object, empty or from (serialized? - $('#yourForm').serialize()) existing form, and then attach the input file.

For the PHP process you can use something like this:

//print_r($_FILES);
$fileName = $_FILES['file']['name'];
$fileType = $_FILES['file']['type'];
$fileError = $_FILES['file']['error'];
$fileContent = file_get_contents($_FILES['file']['tmp_name']);

if($fileError == UPLOAD_ERR_OK){
   //Processes your file here
}else{
   switch($fileError){
     case UPLOAD_ERR_INI_SIZE:   
          $message = 'Error al intentar subir un archivo que excede el tamao permitido.';
          break;
     case UPLOAD_ERR_FORM_SIZE:  
          $message = 'Error al intentar subir un archivo que excede el tamao permitido.';
          break;
     case UPLOAD_ERR_PARTIAL:    
          $message = 'Error: no termin la accin de subir el archivo.';
          break;
     case UPLOAD_ERR_NO_FILE:    
          $message = 'Error: ningn archivo fue subido.';
          break;
     case UPLOAD_ERR_NO_TMP_DIR: 
          $message = 'Error: servidor no configurado para carga de archivos.';
          break;
     case UPLOAD_ERR_CANT_WRITE: 
          $message= 'Error: posible falla al grabar el archivo.';
          break;
     case  UPLOAD_ERR_EXTENSION: 
          $message = 'Error: carga de archivo no completada.';
          break;
     default: $message = 'Error: carga de archivo no completada.';
              break;
    }
      echo json_encode(array(
               'error' => true,
               'message' => $message
            ));
}
formData.append('file', $('#file')[0].files[0]);
undefined
console.log(formData)
_proto_

This should be the accepted answer.

Not supported by IE 9, in case some is stuck in the same hell as I

var formData = new FormData();     formData.append('file', document.getElementById('file').files[0]);     $.ajax({            url : $("form[name='uploadPhoto']").attr("action"),            type : 'POST',            data : formData,            processData: false,  // tell jQuery not to process the data            contentType: false,  // tell jQuery not to set contentType            success : function(data) {                console.log(data);                alert(data);            }     });

javascript - jQuery Ajax File Upload - Stack Overflow

javascript jquery ajax post file-upload
Rectangle 27 83

You cannot upload files using XMLHttpRequest (Ajax). You can simulate the effect using an iframe or Flash. Try the SWF (Flash) uploader SWFUpload.

Or the excellent jQuery Form Plugin that posts your files through an iframe to get the effect.

Yes, you can POST to an iframe and capture the file there. I have very limited experience with this though, so I can't really comment on it.

Small remark: in latest versions of chrome and firefox it is possible, stackoverflow.com/questions/4856917/

javascript - How can I upload files asynchronously? - Stack Overflow

javascript jquery ajax asynchronous upload