我正在从URI中获取图像的斑点,以将其发送到服务器以进行存储。我使用get请求获取图像,并且一切正确,但是post请求有问题。服务器接收到的Blob的大小始终为0。我确信可以正确获取图像的Blob,因为在将Blob转换为base64之后,可以在前端显示它。 这是代码。
const url = "https://lh3.googleusercontent.com/a-/AOh14Gj1THuWiRu7Vpn85YETJN-aMui7NE8bpnNWOzdi"
var x, base64data;
const scope = this
var formData = new FormData();
var request = new XMLHttpRequest();
request.responseType = "blob";
request.onload = function () {
const blob = request.response
formData.append("file", blob.data);
console.log(blob.data)
//Converting the image to base64 so i could display it,
//and make sure that the blob received is not corrupted
const fileReaderInstance = new FileReader();
fileReaderInstance.readAsDataURL(blob);
fileReaderInstance.onload = () => {
base64data = fileReaderInstance.result;
scope.setState({base64data: base64data})
}
//Sending the blob to the server
x = new XMLHttpRequest();
x.open("POST",`${link}images/upload/${data.id}`,true);
x.setRequestHeader("Content-type", "image/jpeg");
x.setRequestHeader("Content-Length", formData.length);
x.send(formData);
}
request.open("GET", url);
request.send();
console.log(blob.data)
显示
Object {
"blobId": "69B8ACFE-5E31-4F16-84D8-002B17399F7E",
"name": "unnamed.jpg",
"offset": 0,
"size": 74054,
"type": "image/jpeg",
}
其他服务器端代码。
router.post('/upload/:id', upload.single('file'), async (req, res) => {
console.log(req.file)
const imgId = req.file.id
const id = req.params.id;
if (!id) return res.send({ error: "Missing playerID" });
if (!idValidator.isMongoId(id))
return res.send({ error: "Invalid Id" })
const player = await Player.findById(id)
if (!player)
return res.send({ error: "Player does not exists" })
const oldImg = player.photo;
if(oldImg && oldImg.toString() !== "5d3ae42c3f2b2c379c361652"){
await Images.findByIdAndDelete(oldImg)
}
player.photo = imgId;
const updatedPlayer = await Player.findByIdAndUpdate(id, player,{new:true})
return res.send({player: updatedPlayer,msg:"Photo Updated!"})
});
console.log(req.file)
显示以下内容。
{ fieldname: 'file',
originalname: 'unnamed.jpg',
encoding: '7bit',
mimetype: 'image/jpeg',
id: 5e780359fbea1452b8409a3e,
filename: '9cdeec500a17eccbb302d8571058da59.jpg',
metadata: null,
bucketName: 'images',
chunkSize: 261120,
size: 0,
md5: 'd41d8cd98f00b204e9800998ecf8427e',
uploadDate: 2020-03-23T00:31:21.640Z,
contentType: 'image/jpeg' }
答案 0 :(得分:0)
经过长时间的搜索,我发现了这一点,并且效果也不错!!!!
postPicture(data) {
const apiUrl = `${link}images/upload/${data.id}`;
const uri = "https://lh3.googleusercontent.com/a-/AOh14Gj1THuWiRu7Vpn85YETJN-aMui7NE8bpnNWOzdi";
const fileType = "jpeg";
const formData = new FormData();
formData.append('file', {
uri,
name: `photo.${fileType}`,
type: `image/${fileType}`,
});
const options = {
method: 'POST',
body: formData,
headers: {
Accept: 'application/json',
'Content-Type': 'multipart/form-data',
},
};
return fetch(apiUrl, options);
}