如何在nodejs中上传文件

如何在nodejs中上传文件

问题描述:

我是nodejs和firebase的新手,但我需要上传文件。我看到this教程,但无法获得太多。我完全困惑。在这个教程中,是传递选择文件的函数? 代码:如何在nodejs中上传文件

const keyFilename = "./my-private-api-key-file.json"; //replace this with api key file 
const projectId = "my-project-id-should-go-here" //replace with your project id 
const bucketName = `${projectId}.appspot.com`; 

const mime = require('mime'); 
const gcs = require('@google-cloud/storage')({ 
    projectId, 
    keyFilename 
}); 

const bucket = gcs.bucket(bucketName); 

const filePath = `./package.json`; 
const uploadTo = `subfolder/package.json`; 
const fileMime = mime.lookup(filePath); 

bucket.upload(filePath, { 
    destination: uploadTo, 
    public: true, 
    metadata: { 
     contentType: fileMime, 
     cacheControl: "public, max-age=300" 
    } 
}, function (err, file) { 
    if (err) { 
     console.log(err); 
     return; 
    } 
    console.log(createPublicFileURL(uploadTo)); 
}); 

function createPublicFileURL(storageName) { 
    return `http://storage.googleapis.com/${bucketName}/${encodeURIComponent(storageName)}`; 
} 

我要上传文件时,用户选择了一个文件。任何人都可以提供我一些启动?谢谢。

您所遵循的教程的目的是为了在文件上传到服务器之后处理文件。这对于服务(如Heroku或OpenShift,如本教程中提到的)适用于不会永久保存上载内容的临时文件系统。

您应该尝试遵循this tutorial而不是,它解释了如何使用AJAX构建前端用户界面。一旦你这样做了,那么你可能需要按照你的问题中链接的教程来获得这些文件永久存储。

希望这有助于。

使用多方库它帮助了我很多在我当前nodejs项目