使用 gcs 上传签名网址的图像上传问题 |反应 JS.



使用它来生成GCS上传签名网址v4 https://github.com/GoogleCloudPlatform/python-docs-samples/blob/master/storage/cloud-client/storage_generate_upload_signed_url_v4.py#L27

如上所述,我已经使用此功能"generate_upload_signed_url_v4"生成了上传签名网址,并且我也尝试使用 GSUTILgsutil signurl -m PUT service_account.json gs://<bucket>/file.png 我正在制作一个演示,我需要将 PDF、PNG 上传到 GCS 存储桶。文件上传就是文件。但是当我在GCS存储控制台中预览文件并从链接URL PDF下载/预览文件时
,就可以了。但是PNG不知何故损坏了,无法打开/预览。 我正在使用Chrome '81.0.4044.138'

当我使用文本编辑器进一步预览PNG文件时,它在文件顶部包含一些标题内容。 即------WebKitFormBoundarysZ3BDVaNOhqwENsp Content-Disposition: form-data; name="file"; filename="test.png" Content-Type: image/png 因此,如果我们从文件顶部删除它,文件将打开正常。

我创建了一个示例 React 项目,可以在此处访问

演示:https://github.com/qaisershehzad/upload-gcs

我正在使用此代码进行文件上传

' 常量网址 = "https://storage.googleapis.com//file.png.png?X-Goog-Algorithm=GOOG4-RSA-SHA256&X-Goog-Credential=gitlab-ci%.iam.gserviceaccount.com%2F20200521%2Fauto%2Fstorage%2Fgoog4_request&X-Goog-Date=20200521T175304Z&X-Goog-Expires=36000&X-Goog-SignedHeaders=content-type%3Bhost&X-Goog-Signature=">

const data = new FormData()
data.append('file', this.state.selectedFile)
var xhr = new XMLHttpRequest();
xhr.open('PUT', url, true);
xhr.setRequestHeader("Content-type", "application/octet-stream");

xhr.onload = function (response) {
console.log('on-load', response);
};
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
console.log("Status OK")
} else {
console.log("Status not 200")
}
}
};
xhr.onerror = function (response) {
console.log("Response error", response)
};
xhr.upload.onprogress = function (evt) {
// For uploads
if (evt.lengthComputable) {
var percentComplete = parseInt((evt.loaded / evt.total) * 100);
console.log("progress", percentComplete)
}
}
xhr.send(data);`

我也在Android上尝试了同样的事情,并面临同样的问题。在顶部的Png中,添加了这些标题字符串,不允许打开Png文件。

使用此 CURL 请求,Png 上传工作正常。 curl -X PUT -H 'Content-Type: application/octet-stream' --upload-filen file.png 'https://storage.googleapis.com//file.png?X-Goog-Algorithm=GOOG4-RSA-SHA256&X-Goog-Credential=gitlab-ci%.iam.gserviceaccount.com%2F20200521%2Fauto%2Fstorage%2Fgoog4_request&X-Goog-Date=20200521T175304Z&X-Goog-Expires=36000&X-Goog-SignedHeaders=content-type%3Bhost&X-Goog-Signature='

如果有人可以帮助解决此问题,那将很有帮助。

实际上您正在发送导致问题的FormData,您将看到文件被上传,但是当您检索文件时,其内容会有所不同,以防图像可能图像不会呈现。

cURL 正常工作的原因,因为您直接发送的是文件而不是 FormData。

要修复这种情况,请直接将文件传递给 ajax,如下所示:

const file = this.state.selectedFile;
ajax.setRequestHeader('Content-Type', file.type);    
ajax.send(file); // direct file not FormData

最新更新