gpt4 book ai didi

node.js - 将文件上传到 Azure Blob 存储时遇到困难

转载 作者:行者123 更新时间:2023-12-03 03:22:22 26 4
gpt4 key购买 nike

我目前正在开发一个项目,需要将文件上传到 Azure Blob 存储。我已经使用 Node.js 和 Express 以及 @azure/storage-blob 库设置了后端。但是,我在前端实现方面面临困难,我可以使用一些指导来确保前端和后端正确集成。前端实现:我尝试使用 React 创建一个基本前端,但在尝试将文件上传到服务器时遇到 400 错误。我不确定我是否正确构建了 fetch() 请求,或者 FormData 对象是否存在任何问题。文件选择和表单提交似乎正常,但上传的文件没有按预期到达后端。

Dashboard.jsx 文件:

import React from 'react';
import { useState } from 'react';

function Dashboard() {
const [selectedFile, setSelectedFile] = useState(null);

const handleFileChange = (e) => {
setSelectedFile(e.target.files[0]);
};

const handleFileUpload = async () => {
try {
const formData = new FormData();
console.log(formData);
formData.append('file', selectedFile);

const response = await fetch('http://localhost:3000/api/upload', {
method: 'POST',
headers: {
'Content-Type': 'multipart/form-data',
},
body: JSON.stringify({
originalname: formData,
mimetype: formData,
size: formData
}),
});

if (response.ok) {
const data = await response.json();
console.log(data.message);
// You can handle success actions here if needed
} else {
console.error('File upload failed.');
// You can handle error actions here if needed
}
} catch (error) {
console.error('Error uploading file:', error);
}
};

return (
<div>
<h1>File Upload</h1>
<input type="file" onChange={handleFileChange} />
<button onClick={handleFileUpload} disabled={!selectedFile}>
Upload File
</button>
</div>
);
}

export default Dashboard

后端实现:在后端,我设置了处理文件上传所需的路由。我正在使用 multer 来处理文件解析和存储。后端代码使用 @azure/storage-blob 库与 Azure Blob 存储交互。但是,由于前端未按预期运行,我无法验证后端是否正常工作。

uploadController.js 文件:

const { BlobServiceClient, StorageSharedKeyCredential } = require('@azure/storage-blob');
const { v4: uuidv4 } = require('uuid');
const multer = require('multer');
const File = require('../models/files');

require('dotenv').config();

const sharedKeyCredential = new StorageSharedKeyCredential(
process.env.AZURE_STORAGE_ACCOUNT_NAME,
process.env.AZURE_STORAGE_ACCOUNT_KEY
);

const blobServiceClient = new BlobServiceClient(
`https://${process.env.AZURE_STORAGE_ACCOUNT_NAME}.blob.core.windows.net`,
sharedKeyCredential
);

const upload = multer({
storage: multer.memoryStorage(),
});

exports.uploadFile = async (req, res, next) => {
try{
const file = req.file;
if (!file) {
return res.status(400).json({ error: 'Please upload a file!' });
}

// Generate a unique filename using UUID
const uniqueFileName = `${uuidv4()}-${file.originalname}`;

// Get a reference to the container
const containerClient = blobServiceClient.getContainerClient(process.env.AZURE_CONTAINER_NAME);

// Upload the file to Azure Blob Storage
const blockBlobClient = containerClient.getBlockBlobClient(uniqueFileName);
await blockBlobClient.uploadData(file.buffer, {
blobHTTPHeaders: {
blobContentType: file.mimetype,
blobContentDisposition: `attachment; filename="${file.originalname}"`,
},
});

// Save file information to the database
const newFile = new File({
filename: file.originalname,
fileType: file.mimetype,
fileSize: file.size,
fileKey: uniqueFileName,
fileURL: blockBlobClient.url,
});

await newFile.save();

return res.status(201).json({ message: 'File uploaded successfully!', file: newFile });
} catch (error) {
console.log(error);
return res.status(500).json({ error: 'Internal server error!' });
}
}

如果您能帮助我改进使用 fetch() 上传文件的前端代码,我将不胜感激。此外,如果有人可以检查我的后端代码并提出任何潜在的改进或调试步骤,这将会很有帮助。

如果您能帮助我改进使用 fetch() 上传文件的前端代码,我将不胜感激。此外,如果有人可以检查我的后端代码并提出任何潜在的改进或调试步骤,这将会很有帮助。

如果有人帮助我改进使用 fetch() 上传文件的前端代码,我将不胜感激。此外,如果有人可以检查我的后端代码并提出任何潜在的改进或调试步骤,这将会很有帮助。

最佳答案

我对您的前端代码进行了一些更改,并且能够将文件作为 blob 上传到我的存储帐户容器。

代码:

Dashboard.jsx:

import { useState } from 'react';
import axios from 'axios';

export default function FileUploader() {
const [selectedFile, setSelectedFile] = useState(null);

const handleFileUpload = async () => {
if (selectedFile) {
try {
const reader = new FileReader();
reader.readAsDataURL(selectedFile);
reader.onloadend = async () => {
const base64File = reader.result.split(',')[1];

await axios.post('/api/upload', { base64File, filename: selectedFile.name });
};
} catch (error) {
console.error(error);
}
}
};

const handleFileChange = (event) => {
const file = event.target.files[0];
setSelectedFile(file);
};

return (
<div>
<input type="file" accept=".txt" onChange={handleFileChange} />
<button onClick={handleFileUpload}>Upload File to storage account</button>
</div>
);
}

upload.js:

import { BlobServiceClient } from '@azure/storage-blob';

export default async function handler(req, res) {
if (req.method === 'POST') {
try {
const { base64File, filename } = req.body;

const storageAccount = '<storage_name>';
const containerName = '<container_name>';
const accessKey = '<storage_key>';
const connectionString = `<connec_string>`;

const blobServiceClient = BlobServiceClient.fromConnectionString(connectionString);

const containerClient = blobServiceClient.getContainerClient(containerName);
const fileBuffer = Buffer.from(base64File, 'base64');
const blockBlobClient = containerClient.getBlockBlobClient(filename);
await blockBlobClient.uploadData(fileBuffer, { blobHTTPHeaders: { blobContentType: 'text/plain' } });

res.status(200).json({ message: 'File uploaded successfully' });
} catch (error) {
res.status(500).json({ error: 'Error occurred' });
}
} else {
res.status(405).json({ error: 'Method not allowed' });
}
}

index.js:

import FileUploader from '../components/Dashboard';

export default function Home() {
return (
<div>
<h1>File Upload</h1>
<FileUploader />
</div>
);
}

输出:

运行成功如下,

enter image description here

通过上述输出URL,我在浏览器中得到了以下结果。我单击选择文件来选择要作为 blob 上传的文件,然后单击将文件上传到存储帐户

enter image description here

文件已作为 Blob 成功上传到我的存储帐户容器,如下所示,

enter image description here

关于node.js - 将文件上传到 Azure Blob 存储时遇到困难,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76798119/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com