问题描述
我四处搜寻,但找不到任何有用的信息。 我正在尝试使用REST API将文件上传到项目中的Google云存储桶,但是我所获得的只是存储桶中的二进制文件,而不是实际文件。 按照Documentation中的说明使用curl上传可以正常工作,例如,我可以将png上传到我的存储桶中。 我正在使用Vue.js和axios发出请求。 这是表单的代码:
<template>
<div>
<div id="form">
<form @submit.prevent="postFiles" enctype="multipart/form-data">
<input type="file" @change="previewFiles" multiple />
<input type="submit" value="Send file" />
</form>
</div>
</div>
</template>
<script>
export default {
name: "InsertFile",data() {
return {
file: "",};
},methods: {
previewFiles(event) { //I use this just for the debug
console.log(event.target.files);
this.file = event.target.files;
},postFiles(){
this.$emit('insert-file',this.file);
}
},};
</script>
这是视图的代码
<template>
<div class="upload">
<h1>Here you can upload your files</h1>
<InsertFile @insert-file="postFile" />
</div>
</template>
<script>
import InsertFile from "../components/InsertFile";
import axios from "axios";
let token='exampletoken'
let config = {
headers: {
'content-type': 'multipart/form-data',Authorization: "Bearer " + token,},};
let url =
"https://storage.googleapis.com/upload/storage/v1/b/bucketURL/o?uploadType=media&name=foo.png";
export default {
components: {
InsertFile,methods: {
postFile(path) {
let bodyFormData = new FormData();
bodyFormData.append("image",path[0]);
console.log(bodyFormData);
axios
.post(url,bodyFormData,config)
.then((response) => {
console.log("Response",response.data);
})
.catch((e) => {
console.log("Error: ",e.response.data);
});
},};
</script>
我从这段代码中获得了存储桶中multipart / form-data类型的文件,如何将其上传为png(或任何类型的文件)?
[编辑]
这是现在的表格
<template>
<div>
<div id="form">
<form @submit.prevent="postFiles" enctype="multipart/form-data">
<input type="file" @change="previewFiles" multiple />
<input type="hidden" name="Content-Type" value="image/png">
<input type="submit" value="Send file" />
</form>
</div>
</div>
</template>
这是方法
<script>
import InsertFile from "../components/InsertFile";
import axios from "axios";
let url =
"https://storage.googleapis.com/upload/storage/v1/b/myBucket/o?uploadType=media&name=prova.png";
export default {
components: {
InsertFile,methods: {
postFile(path) {
console.log(path);
let bodyFormData = new FormData();
bodyFormData.append("file",path[0]);
bodyFormData.append("content-type","image/png");
console.log(bodyFormData);
let token ='mytoken'
let config = {
headers: {
Authorization: "Bearer " + token,};
axios
.put(url,config)
.then((response) => {
console.log("Response",response.data);
})
.catch((e) => {
console.log("Error: ",e.response.data);
});
},};
</script>
解决方法
在多部分数据中,您需要将mime类型作为内容类型发送。
例如,使用JPEG,您将发送Content-Type: image/jpeg
如果没有此设置,上载将假定文件类型是默认值,即二进制数据而不是图像。
在您提供的文档的链接中,请查看此OBJECT_CONTENT_TYPE
部分。
引用他们的文档:
您要通过表单上传的文件的MIME类型。如果您未指定内容类型,则Cloud Storage系统在提供内容时默认将其设置为application / octet-stream。
如果可以的话,我建议安装和使用官方NodeJS SDK的存储部分,并在此示例以下:https://cloud.google.com/storage/docs/uploading-objects#storage-upload-object-nodejs
这应该健壮得多,并提供一个立即可用的示例。
使用API的其他功能(例如列表或删除操作)也将变得更加容易。