我需要发送一个视频文件从谷歌云存储到一个api,这个api通常接受fs文件流。但是,这意味着我必须通过下载视频文件并在发送之前将其保存到本地文件中来保存视频文件。如果可能的话,我很想避免这样做。
这就是我目前如何将我的视频文件发送到api,它需要一个fs的重新流。
const filestream = fs.createReadStream('C:/Users/[me]/Downloads/testvid.mp4');
data.append('video',filestream);
axios({
method: 'post',
url: postUrl,
headers: {
'Content-Type': 'multipart/form-data',
...data.getHeaders()
},
data: data
})
我想要做的实际上是从存储桶中抓取文件,在不保存本地的情况下从它中创建一个重新流,并将它传递给我的axios post请求。
const file = await storage.bucket("[bucket]").file("filename.mp4");
fs.createReadStream(file);
我怎样才能做到这一点?
到目前为止,我已经尝试将google流直接传递到它中,并通过导入“stream”创建了一个直通流,但两者都没有工作。如有任何意见,我将不胜感激。
发布于 2022-06-14 23:08:20
在下载对象页面中,您可以在底部看到一个指向创建传输的链接,它使用不同的源和目的地,比如云存储或文件系统。
如果这不是您想要做的,您可以使用它或将它与流传输结合使用。有一个很好的使用Node.js下载流示例如下:
/**
* TODO(developer): Uncomment the following lines before running the sample.
*/
// The ID of your GCS bucket
// const bucketName = 'your-unique-bucket-name';
// The ID of your GCS file
// const fileName = 'your-file-name';
// The filename and file path where you want to download the file
// const destFileName = '/local/path/to/file.txt';
// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');
// Creates a client
const storage = new Storage();
async function streamFileDownload() {
// The example below demonstrates how we can reference a remote file, then
// pipe its contents to a local file.
// Once the stream is created, the data can be piped anywhere (process, sdout, etc)
await storage
.bucket(bucketName)
.file(fileName)
.createReadStream() //stream is created
.pipe(fs.createWriteStream(destFileName))
.on('finish', () => {
// The file download is complete
});
console.log(
`gs://${bucketName}/${fileName} downloaded to ${destFileName}.`
);
}
streamFileDownload().catch(console.error);
发布于 2022-06-23 08:46:14
我遵循的解决方案类似于Alex的建议,但我没有直接从谷歌获得所有东西,而是使用Google上的get请求获取流,并将其作为流传递到我的formdata
中。这样我就可以从远程服务器发送一个文件,而无需下载它。
const downStream = await axios({ method: 'GET', responseType: 'stream', url: url })
var data: FormData = new FormData();
data.append('video', downStream.data);
const response = await axios({
method: 'post',
url: postUrl,
headers: {
'Content-Type': 'multipart/form-data',
...data.getHeaders()
},
data: data,
maxContentLength: Infinity,
maxBodyLength: Infinity,
})
https://stackoverflow.com/questions/72605933
复制相似问题