NextJS Google云存储问题

mgdq6dx1  于 2023-03-08  发布在  Go
关注(0)|答案(1)|浏览(94)

我在NextJS项目上工作,我想在谷歌云上使用一个表单上传文件。我没有得到任何错误,但文件没有得到上传。我试图在下面解释,请让我知道,如果你有任何其他疑问,在帮助我。

前端代码:

export default function Talento() {
    const [getFile, setFile] = useState([]);
        
    function handleFile(e){
        setFile(e.target.files[0]);
    }
        
    async function handleOnSubmit(e){
        // e.preventDefault();
        let formData = new FormData();
        formData.append('file',getFile);
        
        await axios({
            method: 'post',
            url: '/api/mail',
            data: formData,
            headers: {'Content-Type': 'multipart/form-data' }
        }).then(function (response) {
            success()
        }).catch(function (response) {
            //handle error
            notify()
        });
    }

    return (
            <form method="post" encType='multipart/form-data' onSubmit={handleSubmit} id="myForm" autoComplete="off"> 
                <div className="form-group">
                <label htmlFor="linkedin">Adjunta tu curriculum*</label>
                    <input type="file" className="form-control" id="uploadFile" accept="application/pdf" name="uploadFile" onChange={handleFile}/>
                </div>
                <div className="ip-form-btn-outer text-end">
                <button className="btn btn-main">Enviar solicitud</button>
                </div>
            </form>
    )
}

后端代码

import nc from "next-connect";
import onError from "./middleware/middleware";
import multer from "multer";
import path from "path";
import mail from '@sendgrid/mail';
import {google} from 'googleapis'
import { Storage } from '@google-cloud/storage';
           
const GOOGLE_PROJECT_ID = "bucket-id";
const GOOGLE_BUCKET_NAME = "bucket-name";
const GOOGLE_PRIVATE_KEY ="key here"
const GOOGLE_CLIENT_EMAIL = "test@cloud.com"
    
export const config = {
    api: {
        bodyParser: false,
    },
};
    
const handler = nc(onError);
let storage = multer.diskStorage({});
    
let upload = multer({
    storage: storage,
});
    
let uploadFile = upload.single("file");
handler.use(uploadFile);
    
handler.post(async (req, res) => {       
    const googleStorage = new Storage({
        projectId: GOOGLE_PROJECT_ID,
            credentials: {
            client_email: GOOGLE_CLIENT_EMAIL,
            private_key: GOOGLE_PRIVATE_KEY,
        },
    });
          
    const bucket = googleStorage.bucket(GOOGLE_BUCKET_NAME);
    const file = bucket.file(req.file);
    const options = {
        expires: Date.now() + 1 * 60 * 1000, //  1 minute,
        fields: { 'x-goog-meta-test': 'data' },
    };
            
    console.log(await file.generateSignedPostPolicyV4(options));
          
    const [response] = await file.generateSignedPostPolicyV4(options);
    res.status(200).json(response);
})
    
export default handler;

我得到的回应

{
    "url": "https://storage.googleapis.com/magic-storage-bucket/",
    "fields": {
        "x-goog-meta-test": "data",
        "key": {
            "fieldname": "file",
            "originalname": "WSIB coverage.jpg",
            "encoding": "7bit",
            "mimetype": "image/jpeg",
            "destination": "C:\\Users\\intel\\AppData\\Local\\Temp",
            "filename": "fddd2a3b8264bdf557ebb0c0e260df0e",
            "path": "C:\\Users\\intel\\AppData\\Local\\Temp\\fddd2a3b8264bdf557ebb0c0e260df0e",
            "size": 411040
        },
        "x-goog-date": "20220518T111554Z",
        "x-goog-credential": "credentialshere",
        "x-goog-algorithm": "GOOG4-RSA-SHA256",
        "policy": "policy",
        "x-goog-signature": "signature here"
    }
}
iyr7buue

iyr7buue1#

generateSignedPostPolicyV4函数是上载数据的第一步。
获取v4签名的策略文档,以允许用户使用POST请求上载数据
这可在官方文件中找到。
您应该使用从generateSignedPostPolicyV4获得的响应进行另一次获取。希望我找到的repo可以澄清您关于云存储上的上载方法。

相关问题