使用ReactJs从Azure存储文件共享下载文件

pxq42qpu  于 2023-11-21  发布在  React
关注(0)|答案(1)|浏览(171)

我有一个简单的React应用程序,它是使用React-react-app创建的。我有一个名为storage1的Azure存储和一个名为share1的文件共享。在share1下,我有几个文件,比如file1.pdffile2.docx
如何在React JS应用程序中显示这些文件的列表并下载它们?

daupos2t

daupos2t1#

列出这些文件并将其下载到React JS应用程序中。
你可以使用下面的代码列出Azure文件共享中的文件,并将文件下载到你的本地环境。
首先,您需要创建一个目录,并添加一个文件名为**api.jsapp.js**。

API.js

  1. const express = require('express');
  2. const { ShareServiceClient, StorageSharedKeyCredential } = require('@azure/storage-file-share');
  3. const axios = require('axios');
  4. const router = express.Router();
  5. const storageAccountName = "xxxx";
  6. const shareName = "xxxx";
  7. const accountKey = "xxxx";
  8. const sharedKeyCredential = new StorageSharedKeyCredential(storageAccountName, accountKey);
  9. const shareServiceClient = new ShareServiceClient(`https://${storageAccountName}.file.core.windows.net`, sharedKeyCredential);
  10. const directoryName="";
  11. // Route to get the list of files
  12. router.get('/files', async (req, res) => {
  13. try {
  14. const directoryClient = shareServiceClient.getShareClient(shareName).getDirectoryClient(directoryName);
  15. const list=directoryClient.listFilesAndDirectories();
  16. const files = [];
  17. for await (const item of list) {
  18. if (item.kind === 'file') {
  19. files.push(item.name);
  20. }
  21. }
  22. res.json(files);
  23. } catch (error) {
  24. console.error('Error listing files:', error);
  25. res.status(500).json({ error: 'An error occurred while listing files.' });
  26. }
  27. });
  28. async function downloadFileInBrowser(fileName) {
  29. const fileClient = shareServiceClient.getShareClient(shareName).rootDirectoryClient.getFileClient(fileName);
  30. // Get file content from position 0 to the end
  31. const downloadFileResponse = await fileClient.download(0);
  32. return downloadFileResponse.blobBody;
  33. }
  34. router.get('/download/:fileName', async (req, res) => {
  35. const { fileName } = req.params;
  36. try {
  37. const fileContent = await downloadFileInBrowser(fileName);
  38. res.setHeader('Content-Disposition', `attachment; filename="${fileName}"`);
  39. res.setHeader('Content-Type', 'application/octet-stream');
  40. res.send(fileContent);
  41. } catch (error) {
  42. console.error('Error downloading file:', error);
  43. res.status(500).json({ error: 'An error occurred while downloading the file.' });
  44. }
  45. });
  46. module.exports = router;

字符串

app.js

  1. const express = require('express');
  2. const cors = require('cors');
  3. const apiRouter = require('./api');
  4. const app = express();
  5. const port = process.env.PORT || 5000;
  6. app.use(cors());
  7. app.use('/api', apiRouter);
  8. app.listen(port, () => {
  9. console.log(`Express app listening on port ${port}`);
  10. });


接下来,在react目录中创建**Filelist.js**

FileList.js

  1. import React, { useState, useEffect } from 'react';
  2. import axios from 'axios';
  3. function FileList() {
  4. const [fileList, setFileList] = useState([]);
  5. useEffect(() => {
  6. async function fetchData() {
  7. try {
  8. const response = await axios.get('http://localhost:5000/api/files');
  9. setFileList(response.data);
  10. } catch (error) {
  11. console.error('Error fetching files:', error);
  12. }
  13. }
  14. fetchData();
  15. }, []);
  16. const downloadFile = async (fileName) => {
  17. try {
  18. const response = await axios.get(`http://localhost:5000/api/download/${fileName}`, { responseType: 'blob' });
  19. const url = window.URL.createObjectURL(new Blob([response.data]));
  20. const a = document.createElement('a');
  21. a.href = url;
  22. a.download = fileName;
  23. a.click();
  24. window.URL.revokeObjectURL(url);
  25. } catch (error) {
  26. console.error('Error downloading file:', error);
  27. }
  28. };
  29. return (
  30. <div>
  31. <h1>Files from Azure file share</h1>
  32. <ul>
  33. {fileList.map((file, index) => (
  34. <li key={index}>
  35. {file}
  36. <button onClick={() => downloadFile(file)}>Download</button>
  37. </li>
  38. ))}
  39. </ul>
  40. </div>
  41. );
  42. }
  43. export default FileList;


现在我们应该运行后端代码,它成功运行如下:


的数据
然后,我运行了前端代码,它也成功运行如下:



它在浏览器中打开,如下所示。它列出了Azure文件共享中的文件,您可以单击下载按钮下载文件。


**参考:**适用于JavaScript的Azure存储文件共享客户端库|微软学习

展开查看全部

相关问题