How to make my HTTP request behave the same as a formJavaScript post request like a form submitHow to manage a redirect request after a jQuery Ajax callHTTP GET request in JavaScript?How can I make a time delay in Python?How to make a chain of function decorators?How to make a flat list out of list of listsHow do I make the first letter of a string uppercase in JavaScript?Cannot display HTML stringHow do you add an enctype attribute to a FormData() object?Jersey unsupported media type while using @FormDataParam

Responsibility for visa checking

How were concentration and extermination camp guards recruited?

How to split a string in two substrings of same length using bash?

Why do guitarists wave their guitars?

What is a simple, physical situation where complex numbers emerge naturally?

How to make a setting relevant?

What is the right way to float a home lab?

Replace only 2nd, 3rd, nth...character and onwards

Metal bar on DMM PCB

1980s (or earlier) book where people live a long time but they have short memories

Explain Ant-Man's "not it" scene from Avengers: Endgame

Building a road to escape Earth's gravity by making a pyramid on Antartica

Can you please explain this joke: "I'm going bananas is what I tell my bananas before I leave the house"?

Is the decompression of compressed and encrypted data without decryption also theoretically impossible?

Opposite of "Squeaky wheel gets the grease"

What happens if you do emergency landing on a US base in middle of the ocean?

Secure offsite backup, even in the case of hacker root access

Does any lore text explain why the planes of Acheron, Gehenna, and Carceri are the alignment they are?

Did thousands of women die every year due to illegal abortions before Roe v. Wade?

Does the growth of home value benefit from compound interest?

What happens to foam insulation board after you pour concrete slab?

What does War Machine's "Canopy! Canopy!" line mean in "Avengers: Endgame"?

Wiring from Main to Subpanel

Shrink exponential fraction argument



How to make my HTTP request behave the same as a form


JavaScript post request like a form submitHow to manage a redirect request after a jQuery Ajax callHTTP GET request in JavaScript?How can I make a time delay in Python?How to make a chain of function decorators?How to make a flat list out of list of listsHow do I make the first letter of a string uppercase in JavaScript?Cannot display HTML stringHow do you add an enctype attribute to a FormData() object?Jersey unsupported media type while using @FormDataParam






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








1















I'd need some help with my HTTP request. Here's the setup:



  1. A webpage load an image to a form and send it to a python server running bottle (with the form or a custom http request)

  2. Bottle receive the file, give it as an input for a python script, receive the result and return it to the webpage

On bottle's website there's an example with a form: https://bottlepy.org/docs/dev/tutorial.html#file-uploads I've tried it and it works. Here's the code I used:






<html>
<head>
</head>
<body>
<form action="http://localhost:8080/solve" method="POST" enctype="multipart/form-data" norm="form" id='myForm'>
Select a file: <input type="file" name="upload"/>
<input type="submit" value="Start upload" />
</form>
</body>
</html>





In bottle I have:



@route('/solve', method='POST')
def solve():
file = request.files.get('upload')
name, ext = os.path.splitext(file.filename)
if ext not in ('.png','.jpg','.jpeg'):
return 'File extension not allowed.'
print(file.name)
resolved = sudoku.solve(file.file)
return str(resolved)


This "works", but the form redirects me to localhost:8080 and it's not what I want. I tried putting the target to a hidden iFrame, which prevent the redirection, but I don't manage to access the result in the body of the iFrame...



What I want: Make an HTTP request similar to the one made by the form. So I tried:






<html>

<head> </head>

<body>
<form enctype="multipart/form-data" norm="form" id="myForm">
Select a file:
<input id="fileInput" type="file" name="upload" accept="image/png, image/jpeg, image/jpg" />
<input type="submit" value="Start upload" />
<label class="button-upload" onclick="send()">Upload</label>
</form>

</body>
<script>
var _file = null;

function send()
var file = document.getElementById("fileInput").files[0]
console.log(file)
var url = "http://localhost:8080/solve";

var xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
xhr.setRequestHeader(
"Content-Type",
"multipart/form-data; boundary=---------------------------169461201884497922237853436"
);
var formData = new FormData();

xhr.onreadystatechange = function()
if (xhr.readyState == 4 && xhr.status == 200)
alert(xhr.responseText);

;
formData.append("upload", file);
xhr.send(formData);

</script>

</html>





I've checked with the developper tool in network and the request seems to be the same as the one sent by the form, though bottle can't find the file.



The file = request.files.get('upload') returns None and file = request.files returns <bottle.FormsDict object at 0x7ff437abf400> so there's something but I don't understand how to access it!



Any help would be greatly appreciated!










share|improve this question




























    1















    I'd need some help with my HTTP request. Here's the setup:



    1. A webpage load an image to a form and send it to a python server running bottle (with the form or a custom http request)

    2. Bottle receive the file, give it as an input for a python script, receive the result and return it to the webpage

    On bottle's website there's an example with a form: https://bottlepy.org/docs/dev/tutorial.html#file-uploads I've tried it and it works. Here's the code I used:






    <html>
    <head>
    </head>
    <body>
    <form action="http://localhost:8080/solve" method="POST" enctype="multipart/form-data" norm="form" id='myForm'>
    Select a file: <input type="file" name="upload"/>
    <input type="submit" value="Start upload" />
    </form>
    </body>
    </html>





    In bottle I have:



    @route('/solve', method='POST')
    def solve():
    file = request.files.get('upload')
    name, ext = os.path.splitext(file.filename)
    if ext not in ('.png','.jpg','.jpeg'):
    return 'File extension not allowed.'
    print(file.name)
    resolved = sudoku.solve(file.file)
    return str(resolved)


    This "works", but the form redirects me to localhost:8080 and it's not what I want. I tried putting the target to a hidden iFrame, which prevent the redirection, but I don't manage to access the result in the body of the iFrame...



    What I want: Make an HTTP request similar to the one made by the form. So I tried:






    <html>

    <head> </head>

    <body>
    <form enctype="multipart/form-data" norm="form" id="myForm">
    Select a file:
    <input id="fileInput" type="file" name="upload" accept="image/png, image/jpeg, image/jpg" />
    <input type="submit" value="Start upload" />
    <label class="button-upload" onclick="send()">Upload</label>
    </form>

    </body>
    <script>
    var _file = null;

    function send()
    var file = document.getElementById("fileInput").files[0]
    console.log(file)
    var url = "http://localhost:8080/solve";

    var xhr = new XMLHttpRequest();
    xhr.open("POST", url, true);
    xhr.setRequestHeader(
    "Content-Type",
    "multipart/form-data; boundary=---------------------------169461201884497922237853436"
    );
    var formData = new FormData();

    xhr.onreadystatechange = function()
    if (xhr.readyState == 4 && xhr.status == 200)
    alert(xhr.responseText);

    ;
    formData.append("upload", file);
    xhr.send(formData);

    </script>

    </html>





    I've checked with the developper tool in network and the request seems to be the same as the one sent by the form, though bottle can't find the file.



    The file = request.files.get('upload') returns None and file = request.files returns <bottle.FormsDict object at 0x7ff437abf400> so there's something but I don't understand how to access it!



    Any help would be greatly appreciated!










    share|improve this question
























      1












      1








      1








      I'd need some help with my HTTP request. Here's the setup:



      1. A webpage load an image to a form and send it to a python server running bottle (with the form or a custom http request)

      2. Bottle receive the file, give it as an input for a python script, receive the result and return it to the webpage

      On bottle's website there's an example with a form: https://bottlepy.org/docs/dev/tutorial.html#file-uploads I've tried it and it works. Here's the code I used:






      <html>
      <head>
      </head>
      <body>
      <form action="http://localhost:8080/solve" method="POST" enctype="multipart/form-data" norm="form" id='myForm'>
      Select a file: <input type="file" name="upload"/>
      <input type="submit" value="Start upload" />
      </form>
      </body>
      </html>





      In bottle I have:



      @route('/solve', method='POST')
      def solve():
      file = request.files.get('upload')
      name, ext = os.path.splitext(file.filename)
      if ext not in ('.png','.jpg','.jpeg'):
      return 'File extension not allowed.'
      print(file.name)
      resolved = sudoku.solve(file.file)
      return str(resolved)


      This "works", but the form redirects me to localhost:8080 and it's not what I want. I tried putting the target to a hidden iFrame, which prevent the redirection, but I don't manage to access the result in the body of the iFrame...



      What I want: Make an HTTP request similar to the one made by the form. So I tried:






      <html>

      <head> </head>

      <body>
      <form enctype="multipart/form-data" norm="form" id="myForm">
      Select a file:
      <input id="fileInput" type="file" name="upload" accept="image/png, image/jpeg, image/jpg" />
      <input type="submit" value="Start upload" />
      <label class="button-upload" onclick="send()">Upload</label>
      </form>

      </body>
      <script>
      var _file = null;

      function send()
      var file = document.getElementById("fileInput").files[0]
      console.log(file)
      var url = "http://localhost:8080/solve";

      var xhr = new XMLHttpRequest();
      xhr.open("POST", url, true);
      xhr.setRequestHeader(
      "Content-Type",
      "multipart/form-data; boundary=---------------------------169461201884497922237853436"
      );
      var formData = new FormData();

      xhr.onreadystatechange = function()
      if (xhr.readyState == 4 && xhr.status == 200)
      alert(xhr.responseText);

      ;
      formData.append("upload", file);
      xhr.send(formData);

      </script>

      </html>





      I've checked with the developper tool in network and the request seems to be the same as the one sent by the form, though bottle can't find the file.



      The file = request.files.get('upload') returns None and file = request.files returns <bottle.FormsDict object at 0x7ff437abf400> so there's something but I don't understand how to access it!



      Any help would be greatly appreciated!










      share|improve this question














      I'd need some help with my HTTP request. Here's the setup:



      1. A webpage load an image to a form and send it to a python server running bottle (with the form or a custom http request)

      2. Bottle receive the file, give it as an input for a python script, receive the result and return it to the webpage

      On bottle's website there's an example with a form: https://bottlepy.org/docs/dev/tutorial.html#file-uploads I've tried it and it works. Here's the code I used:






      <html>
      <head>
      </head>
      <body>
      <form action="http://localhost:8080/solve" method="POST" enctype="multipart/form-data" norm="form" id='myForm'>
      Select a file: <input type="file" name="upload"/>
      <input type="submit" value="Start upload" />
      </form>
      </body>
      </html>





      In bottle I have:



      @route('/solve', method='POST')
      def solve():
      file = request.files.get('upload')
      name, ext = os.path.splitext(file.filename)
      if ext not in ('.png','.jpg','.jpeg'):
      return 'File extension not allowed.'
      print(file.name)
      resolved = sudoku.solve(file.file)
      return str(resolved)


      This "works", but the form redirects me to localhost:8080 and it's not what I want. I tried putting the target to a hidden iFrame, which prevent the redirection, but I don't manage to access the result in the body of the iFrame...



      What I want: Make an HTTP request similar to the one made by the form. So I tried:






      <html>

      <head> </head>

      <body>
      <form enctype="multipart/form-data" norm="form" id="myForm">
      Select a file:
      <input id="fileInput" type="file" name="upload" accept="image/png, image/jpeg, image/jpg" />
      <input type="submit" value="Start upload" />
      <label class="button-upload" onclick="send()">Upload</label>
      </form>

      </body>
      <script>
      var _file = null;

      function send()
      var file = document.getElementById("fileInput").files[0]
      console.log(file)
      var url = "http://localhost:8080/solve";

      var xhr = new XMLHttpRequest();
      xhr.open("POST", url, true);
      xhr.setRequestHeader(
      "Content-Type",
      "multipart/form-data; boundary=---------------------------169461201884497922237853436"
      );
      var formData = new FormData();

      xhr.onreadystatechange = function()
      if (xhr.readyState == 4 && xhr.status == 200)
      alert(xhr.responseText);

      ;
      formData.append("upload", file);
      xhr.send(formData);

      </script>

      </html>





      I've checked with the developper tool in network and the request seems to be the same as the one sent by the form, though bottle can't find the file.



      The file = request.files.get('upload') returns None and file = request.files returns <bottle.FormsDict object at 0x7ff437abf400> so there's something but I don't understand how to access it!



      Any help would be greatly appreciated!






      <html>
      <head>
      </head>
      <body>
      <form action="http://localhost:8080/solve" method="POST" enctype="multipart/form-data" norm="form" id='myForm'>
      Select a file: <input type="file" name="upload"/>
      <input type="submit" value="Start upload" />
      </form>
      </body>
      </html>





      <html>
      <head>
      </head>
      <body>
      <form action="http://localhost:8080/solve" method="POST" enctype="multipart/form-data" norm="form" id='myForm'>
      Select a file: <input type="file" name="upload"/>
      <input type="submit" value="Start upload" />
      </form>
      </body>
      </html>





      <html>

      <head> </head>

      <body>
      <form enctype="multipart/form-data" norm="form" id="myForm">
      Select a file:
      <input id="fileInput" type="file" name="upload" accept="image/png, image/jpeg, image/jpg" />
      <input type="submit" value="Start upload" />
      <label class="button-upload" onclick="send()">Upload</label>
      </form>

      </body>
      <script>
      var _file = null;

      function send()
      var file = document.getElementById("fileInput").files[0]
      console.log(file)
      var url = "http://localhost:8080/solve";

      var xhr = new XMLHttpRequest();
      xhr.open("POST", url, true);
      xhr.setRequestHeader(
      "Content-Type",
      "multipart/form-data; boundary=---------------------------169461201884497922237853436"
      );
      var formData = new FormData();

      xhr.onreadystatechange = function()
      if (xhr.readyState == 4 && xhr.status == 200)
      alert(xhr.responseText);

      ;
      formData.append("upload", file);
      xhr.send(formData);

      </script>

      </html>





      <html>

      <head> </head>

      <body>
      <form enctype="multipart/form-data" norm="form" id="myForm">
      Select a file:
      <input id="fileInput" type="file" name="upload" accept="image/png, image/jpeg, image/jpg" />
      <input type="submit" value="Start upload" />
      <label class="button-upload" onclick="send()">Upload</label>
      </form>

      </body>
      <script>
      var _file = null;

      function send()
      var file = document.getElementById("fileInput").files[0]
      console.log(file)
      var url = "http://localhost:8080/solve";

      var xhr = new XMLHttpRequest();
      xhr.open("POST", url, true);
      xhr.setRequestHeader(
      "Content-Type",
      "multipart/form-data; boundary=---------------------------169461201884497922237853436"
      );
      var formData = new FormData();

      xhr.onreadystatechange = function()
      if (xhr.readyState == 4 && xhr.status == 200)
      alert(xhr.responseText);

      ;
      formData.append("upload", file);
      xhr.send(formData);

      </script>

      </html>






      javascript python file-upload xmlhttprequest bottle






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Mar 24 at 13:05









      Victor MeunierVictor Meunier

      177




      177






















          1 Answer
          1






          active

          oldest

          votes


















          1














          Your JavaScript code seems fine, except for where you set request headers with xhr.setRequestHeader. FormData handles multipart encoding for you, you don't need to set request headers manually. I just tried it, and it seems to be working fine with bottlepy.



          Overall, change your send() function as follows:



          function send() 
          var file = document.getElementById("fileInput").files[0]
          console.log(file)
          var url = "http://localhost:8080/solve";

          var xhr = new XMLHttpRequest();
          xhr.open("POST", url, true);
          var formData = new FormData();

          xhr.onreadystatechange = function()
          if (xhr.readyState == 4 && xhr.status == 200)
          alert(xhr.responseText);

          ;
          formData.append("upload", file);
          xhr.send(formData);






          share|improve this answer























          • Thank you it worked well, can't believe it was that simple..

            – Victor Meunier
            Mar 24 at 18:07











          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%2f55324087%2fhow-to-make-my-http-request-behave-the-same-as-a-form%23new-answer', 'question_page');

          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes









          1














          Your JavaScript code seems fine, except for where you set request headers with xhr.setRequestHeader. FormData handles multipart encoding for you, you don't need to set request headers manually. I just tried it, and it seems to be working fine with bottlepy.



          Overall, change your send() function as follows:



          function send() 
          var file = document.getElementById("fileInput").files[0]
          console.log(file)
          var url = "http://localhost:8080/solve";

          var xhr = new XMLHttpRequest();
          xhr.open("POST", url, true);
          var formData = new FormData();

          xhr.onreadystatechange = function()
          if (xhr.readyState == 4 && xhr.status == 200)
          alert(xhr.responseText);

          ;
          formData.append("upload", file);
          xhr.send(formData);






          share|improve this answer























          • Thank you it worked well, can't believe it was that simple..

            – Victor Meunier
            Mar 24 at 18:07















          1














          Your JavaScript code seems fine, except for where you set request headers with xhr.setRequestHeader. FormData handles multipart encoding for you, you don't need to set request headers manually. I just tried it, and it seems to be working fine with bottlepy.



          Overall, change your send() function as follows:



          function send() 
          var file = document.getElementById("fileInput").files[0]
          console.log(file)
          var url = "http://localhost:8080/solve";

          var xhr = new XMLHttpRequest();
          xhr.open("POST", url, true);
          var formData = new FormData();

          xhr.onreadystatechange = function()
          if (xhr.readyState == 4 && xhr.status == 200)
          alert(xhr.responseText);

          ;
          formData.append("upload", file);
          xhr.send(formData);






          share|improve this answer























          • Thank you it worked well, can't believe it was that simple..

            – Victor Meunier
            Mar 24 at 18:07













          1












          1








          1







          Your JavaScript code seems fine, except for where you set request headers with xhr.setRequestHeader. FormData handles multipart encoding for you, you don't need to set request headers manually. I just tried it, and it seems to be working fine with bottlepy.



          Overall, change your send() function as follows:



          function send() 
          var file = document.getElementById("fileInput").files[0]
          console.log(file)
          var url = "http://localhost:8080/solve";

          var xhr = new XMLHttpRequest();
          xhr.open("POST", url, true);
          var formData = new FormData();

          xhr.onreadystatechange = function()
          if (xhr.readyState == 4 && xhr.status == 200)
          alert(xhr.responseText);

          ;
          formData.append("upload", file);
          xhr.send(formData);






          share|improve this answer













          Your JavaScript code seems fine, except for where you set request headers with xhr.setRequestHeader. FormData handles multipart encoding for you, you don't need to set request headers manually. I just tried it, and it seems to be working fine with bottlepy.



          Overall, change your send() function as follows:



          function send() 
          var file = document.getElementById("fileInput").files[0]
          console.log(file)
          var url = "http://localhost:8080/solve";

          var xhr = new XMLHttpRequest();
          xhr.open("POST", url, true);
          var formData = new FormData();

          xhr.onreadystatechange = function()
          if (xhr.readyState == 4 && xhr.status == 200)
          alert(xhr.responseText);

          ;
          formData.append("upload", file);
          xhr.send(formData);







          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Mar 24 at 14:14









          SumitSumit

          1,0931627




          1,0931627












          • Thank you it worked well, can't believe it was that simple..

            – Victor Meunier
            Mar 24 at 18:07

















          • Thank you it worked well, can't believe it was that simple..

            – Victor Meunier
            Mar 24 at 18:07
















          Thank you it worked well, can't believe it was that simple..

          – Victor Meunier
          Mar 24 at 18:07





          Thank you it worked well, can't believe it was that simple..

          – Victor Meunier
          Mar 24 at 18:07



















          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%2f55324087%2fhow-to-make-my-http-request-behave-the-same-as-a-form%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

          Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

          SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

          은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현