我正在尝试使用 Next JS 并最终使用 Vercel 来处理使用 Google Cloud Storage 上传的图片,但结果喜忧参半。
我从一些文档中上传了一个基本的文件,如下所示:
function NewBet(props) {
const [state, setState] = useState({
src: '',
})
const { src } = state
const registerUser = async (event) => {
event.preventDefault()
//Upload image to Google
const file = src
const filename = encodeURIComponent(file.name)
console.log('filename: ', filename)
const resImg = await fetch(`/api/upload?file=${filename}`)
const url = await resImg.json()
const formData = new FormData()
formData.append('file', filename)
const upload = await fetch(url, {
method: 'POST',
body: formData,
})
if (upload.ok) {
console.log('Uploaded successfully!')
} else {
console.error('Upload failed.')
}
}
const onSelectFile = (e) => {
if (e.target.files && e.target.files.length > 0) {
setState({ ...state, src: e.target.files[0] })
}
}
.....
<form onSubmit={registerUser} className="myForm">
<OCRCompoonent onOCRReturned={handleOCR} onSelectFile={onSelectFile} />
.....
</form>
我的上传看起来像这样:
import { Storage } from '@google-cloud/storage'
export default async function handler(req, res) {
const storage = new Storage({
projectId: process.env.PROJECT_ID,
credentials: {
client_email: process.env.CLIENT_EMAIL,
private_key: process.env.PRIVATE_KEY,
},
})
const bucket = storage.bucket(process.env.BUCKET_NAME)
const file = bucket.file(req.query.file)
const options = {
expires: Date.now() + 1 * 60 * 1000, // 1 minute,
fields: { 'x-goog-meta-test': 'data' },
}
const [response] = await file.generateSignedPostPolicyV4(options)
res.status(200).json(response)
}
这基本上是我的环境变量
所以 1) 我在控制台日志中成功上传了图像,但似乎没有任何内容添加到我的云存储桶中,而数字 2... 当部署到 Vercel 时,我得到...
[clubid]-f98a4d840994ca2053e3.js:1 POST https://xxxxxx.xxxxx.app/club/[object%20Object] net::ERR_ABORTED 500
(anonymous) @ [clubid]-f98a4d840994ca2053e3.js:1
...more error code....
react_devtools_backend.js:2557 Upload failed.
我做错了什么吗?谢谢