Como dije, quiero convertir esa solicitud POST con un archivo a JavaScript. Este código envía una solicitud JSON que contiene un archivo de imagen al servidor.
La función Dart es esta (convertir esto a javascript):
Future postData(User user, VideoGame videoGame, File file) async { Map data = { 'name': user.name, 'contact': user.contact, 'location': { 'country': user.country, 'state': user.state, 'city': user.city }, 'videoGame': { 'name': videoGame.name, 'type': videoGame.type, 'console': videoGame.console, } }; try { String _url = baseUrl + 'insertData'; var uri = Uri.parse(_url); var request = http.MultipartRequest('POST', uri) ..headers.addAll({'Content-type': 'multipart/form-data', 'Accept': 'multipart/form-data'}) ..fields.addAll({'data': json.encode(data)}); request.files.add( http.MultipartFile( 'image', file.readAsBytes().asStream(), file.lengthSync(), filename: file.path.split("/").last ), ); var response = await request.send(); print('Status ${response.statusCode}'); if (response.statusCode == 200) { final respStr = await response.stream.bytesToString(); print(jsonDecode(respStr)); MyALertKey .currentState ?.setState((){}); } } catch (e) { print("Video Games POST error => ${e.toString()}"); } }Debido a que el servidor está escrito en Python, no pude ver que este archivo se envía al servidor (solicitar cuerpo completo).
He escrito esto en JavaScript pero no funciona.
const handleSubmit = async (e) => { e.preventDefault(); var data = new FormData() var blob = new Blob([JSON.stringify({ name: somevalue, contact: somevalue, location: { country: somevalue, state: somevalue, city: somevalue }, videoGame: { name: somevalue, type: somevalue, console: somevalue, } })],{ type: 'application/json' }) data.append('data',blob) data.append('image',file_from_input) try { const res = await fetch('url',{ method:'POST', cache: 'default', mode: 'no-cors', headers: { 'Content-Type': 'multipart/form-data' }, body: data }) let data_ = await res.json() console.log(data_) } catch (e) { console.log(e) } console.log(res.status) // will be 400 bad request }Por favor, ayúdame. Gracias.