Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

551
Views
Convertir la carga de archivos JS con fetch () a python

Tengo que convertir el código js a python. El código js realiza una carga de archivos a través de una solicitud POST, usando fetch(). Este es el código js:

 <input type="file" /> <button onclick="upload()">Upload data</button> <script> upload = async() => { const fileField = document.querySelector('input[type="file"]'); await uploadDoc(fileField.files[0] ); }; uploadDoc = async( file ) => { let fd = new FormData(); fd.append( 'file', file ); fd.append( 'descr', 'demo_upload' ); fd.append( 'title', name ); fd.append( 'contentType', 'text' ); fd.append( 'editor', user ); let resp = await fetch( url, { method: 'POST', mode: 'cors', body: fd }); }; </script>

El código funciona y cumple con los documentos fetch(), proporcionados aquí: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#uploading_a_file

Ahora, cuando intento recrear esto en python, obtengo un código de estado HTTP 500. Este es el código de python:

 from urllib import request from urllib.parse import urlencode import json with open('README.md', 'rb') as f: upload_credentials = { "file": f, "descr": "testing", "title": "READMEE.md", "contentType": "text", "editor": username, } url_for_upload = "" #here you place the upload URL req = request.Request(url_for_upload, method="POST") form_data = urlencode(upload_credentials) form_data = form_data.encode() response = request.urlopen(req, data=form_data) http_status_code = response.getcode() content = response.read() print(http_status_code) print(content)

Sin embargo, esto no funciona y me sale este error:

 raise HTTPError(req.full_url, code, msg, hdrs, fp) urllib.error.HTTPError: HTTP Error 500:

Alguien con experiencia en js y python podría ver qué está mal en el lado de python, o cómo convertir la función fetch() a python.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Creo que el problema es que estás leyendo el archivo en modo binario ( rb ). Solo necesitas r :

 with open('README.md', 'r') as f: # r instead of rb

Sin embargo, sigo recomendando el módulo de requests , que es más utilizado y es más fácil en este caso.

 import requests # pip install requests url = "https://www.example.com/upload_file" headers = { "content-type": "text/plain" # force text file content type } files = { "my_file": ("FILE_NAME.md", open("README.md","r")) # tuple containing file name, and io.BytesIO file buffer } data = { # in case you want to send a request payload too "foo": "bar" } r = requests.post(url, headers=headers, files=files, data=data) if r.status_code == 200: print(r.text) # print response as a string (r.content for bytes, if response is binary like an image)
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!