How to upload resized image in JavaScript and upload to server using Python?












0















I am trying to upload an image to server. Before uploading I modified its sized in JavaScript as shown below. I am using Python script to receive and upload the file:






let canvas;
let array_WH = new Array();
let percent = 50;
let img = new Image();

$(function() {

function ff(height, width, percentage) {

var newHeight = height * (percentage / 100);

var newWidth = width * (percentage / 100);

return [newWidth, newHeight];
}

$("#file_select").change(function(e) {

var fileReader = new FileReader();

fileReader.onload = function(e) {



img.onload = function() {

array_WH = ff(img.height, img.width, percent); //Pavel: changed order to correct

console.log('old width: ' + img.width);
console.log('new width: ' + array_WH[0]);

width = array_WH[0];

height = array_WH[1];

if (canvas) return;

canvas = document.createElement("canvas");

canvas.width = width;

canvas.height = height;

canvas.getContext("2d").drawImage(this, 0, 0, width, height);

// //Line added
//var canvasData = canvas.toDataURL(); //Pavel: also for png can be: toDataURL("image/png");
var canvasData = canvas.toDataURL('image/jpeg', 0.5); //Pavel: sec param is quality from 0 to 1
// //Line edited
this.src = canvasData;
// //Line added
console.log(canvasData.length * 3 / 4, ' bytes');

document.body.appendChild(this); //remove this if you don't want to show it

}

img.src = e.target.result;

}

fileReader.readAsDataURL(e.target.files[0]);

});

});

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>

<h1 class="logo">Upload Picture</h1>
<div id="upload_form_div">
<form id="upload_form" method="POST" enctype="multipart/form-data" action="/Document/upload/">
<input type="file" name="file" capture="camera" id="file_select" />
<input type="submit" value="submit image">
</form>
</div>

<div id="loading" style="display:none;">
Uploading your picture...
</div>





In my views.py, I tried to received the file and move it to upload folder:



@app.route("/Document/Upload/", methods=['POST'])
def getDocumentUpload():
try:
file = request.files['file'] if 'file' in request.files else None
AttachmentFolder= '/Attachment/image/'
filename = secure_filename(file.filename)
strName = filename.split(".")
Link = "%s.%s" %(filename, strName[-1])
# Upload file to destination folder
file.save(os.path.abspath(AttachmentFolder + Link))
except Exception as e:
raise e


However, the image I am receiving at server side is the original image not the resized image that I want.



From some sources I found here and this using php server side script suggested to convert image into base64, sent to server via ajax and decode base64 in server side, it is possible but how can I use base64 object to save image to folder using python and while I'm not using ajax to upload file instead I just using form submit button as normal.



One way I could think of is to modified the file object from upload field to get the resized image instead of origin one, so the rest will be working as it is, but is it possible?



Kindly help me, how can I send the resized image from JavaScript above and receive it in server side using python script? Thanks.










share|improve this question





























    0















    I am trying to upload an image to server. Before uploading I modified its sized in JavaScript as shown below. I am using Python script to receive and upload the file:






    let canvas;
    let array_WH = new Array();
    let percent = 50;
    let img = new Image();

    $(function() {

    function ff(height, width, percentage) {

    var newHeight = height * (percentage / 100);

    var newWidth = width * (percentage / 100);

    return [newWidth, newHeight];
    }

    $("#file_select").change(function(e) {

    var fileReader = new FileReader();

    fileReader.onload = function(e) {



    img.onload = function() {

    array_WH = ff(img.height, img.width, percent); //Pavel: changed order to correct

    console.log('old width: ' + img.width);
    console.log('new width: ' + array_WH[0]);

    width = array_WH[0];

    height = array_WH[1];

    if (canvas) return;

    canvas = document.createElement("canvas");

    canvas.width = width;

    canvas.height = height;

    canvas.getContext("2d").drawImage(this, 0, 0, width, height);

    // //Line added
    //var canvasData = canvas.toDataURL(); //Pavel: also for png can be: toDataURL("image/png");
    var canvasData = canvas.toDataURL('image/jpeg', 0.5); //Pavel: sec param is quality from 0 to 1
    // //Line edited
    this.src = canvasData;
    // //Line added
    console.log(canvasData.length * 3 / 4, ' bytes');

    document.body.appendChild(this); //remove this if you don't want to show it

    }

    img.src = e.target.result;

    }

    fileReader.readAsDataURL(e.target.files[0]);

    });

    });

    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
    <script src="http://malsup.github.com/jquery.form.js"></script>

    <h1 class="logo">Upload Picture</h1>
    <div id="upload_form_div">
    <form id="upload_form" method="POST" enctype="multipart/form-data" action="/Document/upload/">
    <input type="file" name="file" capture="camera" id="file_select" />
    <input type="submit" value="submit image">
    </form>
    </div>

    <div id="loading" style="display:none;">
    Uploading your picture...
    </div>





    In my views.py, I tried to received the file and move it to upload folder:



    @app.route("/Document/Upload/", methods=['POST'])
    def getDocumentUpload():
    try:
    file = request.files['file'] if 'file' in request.files else None
    AttachmentFolder= '/Attachment/image/'
    filename = secure_filename(file.filename)
    strName = filename.split(".")
    Link = "%s.%s" %(filename, strName[-1])
    # Upload file to destination folder
    file.save(os.path.abspath(AttachmentFolder + Link))
    except Exception as e:
    raise e


    However, the image I am receiving at server side is the original image not the resized image that I want.



    From some sources I found here and this using php server side script suggested to convert image into base64, sent to server via ajax and decode base64 in server side, it is possible but how can I use base64 object to save image to folder using python and while I'm not using ajax to upload file instead I just using form submit button as normal.



    One way I could think of is to modified the file object from upload field to get the resized image instead of origin one, so the rest will be working as it is, but is it possible?



    Kindly help me, how can I send the resized image from JavaScript above and receive it in server side using python script? Thanks.










    share|improve this question



























      0












      0








      0








      I am trying to upload an image to server. Before uploading I modified its sized in JavaScript as shown below. I am using Python script to receive and upload the file:






      let canvas;
      let array_WH = new Array();
      let percent = 50;
      let img = new Image();

      $(function() {

      function ff(height, width, percentage) {

      var newHeight = height * (percentage / 100);

      var newWidth = width * (percentage / 100);

      return [newWidth, newHeight];
      }

      $("#file_select").change(function(e) {

      var fileReader = new FileReader();

      fileReader.onload = function(e) {



      img.onload = function() {

      array_WH = ff(img.height, img.width, percent); //Pavel: changed order to correct

      console.log('old width: ' + img.width);
      console.log('new width: ' + array_WH[0]);

      width = array_WH[0];

      height = array_WH[1];

      if (canvas) return;

      canvas = document.createElement("canvas");

      canvas.width = width;

      canvas.height = height;

      canvas.getContext("2d").drawImage(this, 0, 0, width, height);

      // //Line added
      //var canvasData = canvas.toDataURL(); //Pavel: also for png can be: toDataURL("image/png");
      var canvasData = canvas.toDataURL('image/jpeg', 0.5); //Pavel: sec param is quality from 0 to 1
      // //Line edited
      this.src = canvasData;
      // //Line added
      console.log(canvasData.length * 3 / 4, ' bytes');

      document.body.appendChild(this); //remove this if you don't want to show it

      }

      img.src = e.target.result;

      }

      fileReader.readAsDataURL(e.target.files[0]);

      });

      });

      <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
      <script src="http://malsup.github.com/jquery.form.js"></script>

      <h1 class="logo">Upload Picture</h1>
      <div id="upload_form_div">
      <form id="upload_form" method="POST" enctype="multipart/form-data" action="/Document/upload/">
      <input type="file" name="file" capture="camera" id="file_select" />
      <input type="submit" value="submit image">
      </form>
      </div>

      <div id="loading" style="display:none;">
      Uploading your picture...
      </div>





      In my views.py, I tried to received the file and move it to upload folder:



      @app.route("/Document/Upload/", methods=['POST'])
      def getDocumentUpload():
      try:
      file = request.files['file'] if 'file' in request.files else None
      AttachmentFolder= '/Attachment/image/'
      filename = secure_filename(file.filename)
      strName = filename.split(".")
      Link = "%s.%s" %(filename, strName[-1])
      # Upload file to destination folder
      file.save(os.path.abspath(AttachmentFolder + Link))
      except Exception as e:
      raise e


      However, the image I am receiving at server side is the original image not the resized image that I want.



      From some sources I found here and this using php server side script suggested to convert image into base64, sent to server via ajax and decode base64 in server side, it is possible but how can I use base64 object to save image to folder using python and while I'm not using ajax to upload file instead I just using form submit button as normal.



      One way I could think of is to modified the file object from upload field to get the resized image instead of origin one, so the rest will be working as it is, but is it possible?



      Kindly help me, how can I send the resized image from JavaScript above and receive it in server side using python script? Thanks.










      share|improve this question
















      I am trying to upload an image to server. Before uploading I modified its sized in JavaScript as shown below. I am using Python script to receive and upload the file:






      let canvas;
      let array_WH = new Array();
      let percent = 50;
      let img = new Image();

      $(function() {

      function ff(height, width, percentage) {

      var newHeight = height * (percentage / 100);

      var newWidth = width * (percentage / 100);

      return [newWidth, newHeight];
      }

      $("#file_select").change(function(e) {

      var fileReader = new FileReader();

      fileReader.onload = function(e) {



      img.onload = function() {

      array_WH = ff(img.height, img.width, percent); //Pavel: changed order to correct

      console.log('old width: ' + img.width);
      console.log('new width: ' + array_WH[0]);

      width = array_WH[0];

      height = array_WH[1];

      if (canvas) return;

      canvas = document.createElement("canvas");

      canvas.width = width;

      canvas.height = height;

      canvas.getContext("2d").drawImage(this, 0, 0, width, height);

      // //Line added
      //var canvasData = canvas.toDataURL(); //Pavel: also for png can be: toDataURL("image/png");
      var canvasData = canvas.toDataURL('image/jpeg', 0.5); //Pavel: sec param is quality from 0 to 1
      // //Line edited
      this.src = canvasData;
      // //Line added
      console.log(canvasData.length * 3 / 4, ' bytes');

      document.body.appendChild(this); //remove this if you don't want to show it

      }

      img.src = e.target.result;

      }

      fileReader.readAsDataURL(e.target.files[0]);

      });

      });

      <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
      <script src="http://malsup.github.com/jquery.form.js"></script>

      <h1 class="logo">Upload Picture</h1>
      <div id="upload_form_div">
      <form id="upload_form" method="POST" enctype="multipart/form-data" action="/Document/upload/">
      <input type="file" name="file" capture="camera" id="file_select" />
      <input type="submit" value="submit image">
      </form>
      </div>

      <div id="loading" style="display:none;">
      Uploading your picture...
      </div>





      In my views.py, I tried to received the file and move it to upload folder:



      @app.route("/Document/Upload/", methods=['POST'])
      def getDocumentUpload():
      try:
      file = request.files['file'] if 'file' in request.files else None
      AttachmentFolder= '/Attachment/image/'
      filename = secure_filename(file.filename)
      strName = filename.split(".")
      Link = "%s.%s" %(filename, strName[-1])
      # Upload file to destination folder
      file.save(os.path.abspath(AttachmentFolder + Link))
      except Exception as e:
      raise e


      However, the image I am receiving at server side is the original image not the resized image that I want.



      From some sources I found here and this using php server side script suggested to convert image into base64, sent to server via ajax and decode base64 in server side, it is possible but how can I use base64 object to save image to folder using python and while I'm not using ajax to upload file instead I just using form submit button as normal.



      One way I could think of is to modified the file object from upload field to get the resized image instead of origin one, so the rest will be working as it is, but is it possible?



      Kindly help me, how can I send the resized image from JavaScript above and receive it in server side using python script? Thanks.






      let canvas;
      let array_WH = new Array();
      let percent = 50;
      let img = new Image();

      $(function() {

      function ff(height, width, percentage) {

      var newHeight = height * (percentage / 100);

      var newWidth = width * (percentage / 100);

      return [newWidth, newHeight];
      }

      $("#file_select").change(function(e) {

      var fileReader = new FileReader();

      fileReader.onload = function(e) {



      img.onload = function() {

      array_WH = ff(img.height, img.width, percent); //Pavel: changed order to correct

      console.log('old width: ' + img.width);
      console.log('new width: ' + array_WH[0]);

      width = array_WH[0];

      height = array_WH[1];

      if (canvas) return;

      canvas = document.createElement("canvas");

      canvas.width = width;

      canvas.height = height;

      canvas.getContext("2d").drawImage(this, 0, 0, width, height);

      // //Line added
      //var canvasData = canvas.toDataURL(); //Pavel: also for png can be: toDataURL("image/png");
      var canvasData = canvas.toDataURL('image/jpeg', 0.5); //Pavel: sec param is quality from 0 to 1
      // //Line edited
      this.src = canvasData;
      // //Line added
      console.log(canvasData.length * 3 / 4, ' bytes');

      document.body.appendChild(this); //remove this if you don't want to show it

      }

      img.src = e.target.result;

      }

      fileReader.readAsDataURL(e.target.files[0]);

      });

      });

      <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
      <script src="http://malsup.github.com/jquery.form.js"></script>

      <h1 class="logo">Upload Picture</h1>
      <div id="upload_form_div">
      <form id="upload_form" method="POST" enctype="multipart/form-data" action="/Document/upload/">
      <input type="file" name="file" capture="camera" id="file_select" />
      <input type="submit" value="submit image">
      </form>
      </div>

      <div id="loading" style="display:none;">
      Uploading your picture...
      </div>





      let canvas;
      let array_WH = new Array();
      let percent = 50;
      let img = new Image();

      $(function() {

      function ff(height, width, percentage) {

      var newHeight = height * (percentage / 100);

      var newWidth = width * (percentage / 100);

      return [newWidth, newHeight];
      }

      $("#file_select").change(function(e) {

      var fileReader = new FileReader();

      fileReader.onload = function(e) {



      img.onload = function() {

      array_WH = ff(img.height, img.width, percent); //Pavel: changed order to correct

      console.log('old width: ' + img.width);
      console.log('new width: ' + array_WH[0]);

      width = array_WH[0];

      height = array_WH[1];

      if (canvas) return;

      canvas = document.createElement("canvas");

      canvas.width = width;

      canvas.height = height;

      canvas.getContext("2d").drawImage(this, 0, 0, width, height);

      // //Line added
      //var canvasData = canvas.toDataURL(); //Pavel: also for png can be: toDataURL("image/png");
      var canvasData = canvas.toDataURL('image/jpeg', 0.5); //Pavel: sec param is quality from 0 to 1
      // //Line edited
      this.src = canvasData;
      // //Line added
      console.log(canvasData.length * 3 / 4, ' bytes');

      document.body.appendChild(this); //remove this if you don't want to show it

      }

      img.src = e.target.result;

      }

      fileReader.readAsDataURL(e.target.files[0]);

      });

      });

      <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
      <script src="http://malsup.github.com/jquery.form.js"></script>

      <h1 class="logo">Upload Picture</h1>
      <div id="upload_form_div">
      <form id="upload_form" method="POST" enctype="multipart/form-data" action="/Document/upload/">
      <input type="file" name="file" capture="camera" id="file_select" />
      <input type="submit" value="submit image">
      </form>
      </div>

      <div id="loading" style="display:none;">
      Uploading your picture...
      </div>






      javascript jquery python-2.7






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 22 '18 at 6:10









      Anki

      24118




      24118










      asked Nov 22 '18 at 5:57









      Houy NarunHouy Narun

      246523




      246523
























          0






          active

          oldest

          votes











          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          autoActivateHeartbeat: false,
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53424695%2fhow-to-upload-resized-image-in-javascript-and-upload-to-server-using-python%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          0






          active

          oldest

          votes








          0






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes
















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53424695%2fhow-to-upload-resized-image-in-javascript-and-upload-to-server-using-python%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          MongoDB - Not Authorized To Execute Command

          in spring boot 2.1 many test slices are not allowed anymore due to multiple @BootstrapWith

          How to fix TextFormField cause rebuild widget in Flutter