1

Here is the html element we are trying to attach a file to:

<input id="uploaded_file_file_for_upload" class="file optional" type="file" name="uploaded_file[file_for_upload]">

User already selects a file for the element above. What we need to do is to remove the current file selection and attach a new file to it. The new file is an image file and is saved in a canvas element. Here is the js code for new file:

 function resize(image, width, height) {
      var mainCanvas = document.createElement("canvas");
      mainCanvas.width = width;
      mainCanvas.height = height;
      var ctx = mainCanvas.getContext("2d");
      alert(width + '    resize to    ' + height);
      ctx.drawImage(image, 0, 0, width, height);
  .....(remove current and attach the new file to the elelment#uploaded_file_file_for_upload)
   };

We tried the following to attach and it did not work:

$('#uploaded_file_file_for_upload').attr('src', mainCanvas.toDataURL("image/jpeg"));

The problem may be that it is not an image element. What's the right way to remove and attach a file type?

halfer
  • 19,824
  • 17
  • 99
  • 186
user938363
  • 9,990
  • 38
  • 137
  • 303
  • Possible duplicate of [Pre-Populate HTML form file input](http://stackoverflow.com/questions/16365668/pre-populate-html-form-file-input) – Mark Schultheiss Nov 11 '15 at 18:50
  • Possible duplicate of http://stackoverflow.com/questions/29841147/input-file-to-array-javascript-jquery/ . Not possible to alter to `FileList` object . Try converting `FileList` object to array, using `.splice()` to remove file from array , insert new file , `POST` array containing new file object . – guest271314 Nov 11 '15 at 18:58

1 Answers1

1

The short answer is you can't. The only way to upload a file is to ship the file selected by the user, with no change.

The only way to do exactly what you are trying to do here is using :

  • a native app
  • a hybrid app with native plugin
  • via a browser plugin (flash, chrome app...)

Unless, the browser security policy will block you.

Two workarounds could be:

  • send the original file and resize it server side (php library, nodejs...)
  • or resize the image as you want, then uploading the base64 encoded image data of the edited image via a POST ajax request to your server, and then write it to a file server side.
Rémi Becheras
  • 14,902
  • 14
  • 51
  • 81