As I said, I want to convert that POST request with a file to JavaScript. This code sends a JSON request which contains an image file to server.
The Dart function is this (convert this to 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()}");
}
}
Because the server written in Python I couldn't see that this file sends to server (request full body).
I have written this in JavaScript but it doesn't work.
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
}
Please help me. Thanks.