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?

2

1 Answer 1

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.
Sign up to request clarification or add additional context in comments.

4 Comments

Resize on client side has less bandwidth cost and offers better customer experience. It is harder to implement compared with service side solution.
Remi Becheras, is text field good to store base64 encoded image data for upload?
text field seems ok for the base64 encoded data which is a string.
Yes, send it as a simple string. Its a string representation of an image.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.