我四处搜寻,但找不到任何有用的东西。我正在尝试使用 REST API 将文件上传到我的项目中的谷歌云存储桶,但我获得的只是存储桶中的二进制文件,而不是实际文件。按照文档中的说明使用 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, bodyFormData, config)
.then((response) => {
console.log("Response", response.data);
})
.catch((e) => {
console.log("Error: ", e.response.data);
});
},
},
};
</script>