如何通过 Gatsby Azure Static Web App 将图像上传到 Azure 数据库

问题描述 投票:0回答:1

我需要通过 gatsby Azure 静态 Web 应用程序上传图像。

目前我正在使用以下“工具”:

  1. Azure 静态 Web 应用程序
  2. Azure SQL 数据库

我的高级想法是:

  1. 在 Gatsby 页面/表单中创建输入类型=“文件”
  2. 调用 REST API 将图像(以及表单的其他字段,如文本、数字等)上传到数据库
  3. 将图像(和其他字段)存储到 Azure sql 数据库列中

可以实施吗?如果是,怎么办? 我可以通过 Gatsby 表单使用 REST-API 调用上传图像吗?

一般问题:使用 Azure“工具”通过 Gatsby 静态 Web 应用程序表单将文件上传到数据库的最佳方法是什么?

请考虑到我只想使用免费的 Azure“工具”。

rest file-upload azure-sql-database gatsby azure-static-web-app
1个回答
0
投票

下面的示例代码适用于 Azure SQL 中的 JSON 文件,它使用 Node.js、REST API 和 Gatsby 将文件上传功能集成到 Web 应用程序中。

  • 要将文件存储在 Azure Blob 存储中,必须首先上传该文件。之后,您可以使用 BULK INSERT 或 OPENROWSET 来访问该文件。
  • 我遵循了 Davide Mauri SO
  • 的“使用 Azure SQL 处理 JSON 文件”

创建数据库范围的凭据

CREATE DATABASE SCOPED CREDENTIAL AzureBlobCredential   
WITH IDENTITY = 'SHARED ACCESS SIGNATURE',
SECRET = 'your_shared_access_signature';

创建外部数据源:

CREATE EXTERNAL DATA SOURCE YourDataSource
WITH (
    TYPE = BLOB_STORAGE,
    LOCATION = 'https://yourblobstorage.blob.core.windows.net/container',
    CREDENTIAL = AzureBlobCredential
);

创建一个用于存储 JSON 数据的表:

CREATE TABLE JSONDataTable (
    ID INT IDENTITY(1,1) PRIMARY KEY,
    JsonData NVARCHAR(MAX)
);

将 JSON 数据上传到表中:

INSERT INTO JSONDataTable (JsonData)
SELECT *
FROM OPENROWSET(
    BULK 'yourjson.json',
    DATA_SOURCE = 'YourDataSource',
    FORMAT = 'JSON'
) AS jsondata;


下面的代码使用 REST API 设置 Node.js Express 服务器来处理文件上传到 Azure SQL。


const express = require('express');
const multer = require('multer');
const sql = require('mssql');
const cors = require('cors');

const app = express();
const port = process.env.PORT || 3000;

// Multer configuration for handling file uploads
const upload = multer({ dest: 'uploads/' });

// Azure SQL database configuration
const config = {
  server: 'your_server.database.windows.net',
  database: 'your_database',
  user: 'your_username',
  password: 'your_password',
  options: {
    encrypt: true,
    trustServerCertificate: false,
    connectionTimeout: 30000,
    enableArithAbort: true
  }
};

// CORS middleware
app.use(cors());

// Endpoint for uploading JSON file and storing it in Azure SQL
app.post('/upload', upload.single('jsonFile'), async (req, res) => {
  try {
    // Connect to Azure SQL
    await sql.connect(config);

    // Read the uploaded JSON file
    const jsonData = require(req.file.path);

    // Insert JSON data into Azure SQL table
    const request = new sql.Request();
    await request.query(`INSERT INTO JSONDataTable (JsonData) VALUES ('${JSON.stringify(jsonData)}')`);

    // Respond with success message
    res.status(200).send('JSON data uploaded successfully!');
  } catch (error) {
    console.error('Error:', error.message);
    res.status(500).send('Internal Server Error');
  } finally {
    sql.close();
  }
});

// Endpoint for querying JSON data from Azure SQL
app.get('/data', async (req, res) => {
  try {
    // Connect to Azure SQL
    await sql.connect(config);

    // Query JSON data from Azure SQL
    const request = new sql.Request();
    const result = await request.query('SELECT * FROM JSONDataTable');

    // Respond with JSON data
    res.status(200).json(result.recordset);
  } catch (error) {
    console.error('Error:', error.message);
    res.status(500).send('Internal Server Error');
  } finally {
    sql.close();
  }
});

// Start the server
app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});

enter image description here

enter image description here

我按照此链接建立了联系表格。

形成盖茨比:


// components/JSONUploadForm.js
import React, { useState } from "react";

const JSONUploadForm = () => {
  const [file, setFile] = useState(null);

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

  const handleSubmit = async (event) => {
    event.preventDefault();
    
    if (!file) {
      alert("Please select a file to upload");
      return;
    }

    const formData = new FormData();
    formData.append("jsonFile", file);

    try {
      const response = await fetch("http://localhost:3000/upload", {
        method: "POST",
        body: formData,
      });

      if (response.ok) {
        alert("JSON file uploaded successfully");
      } else {
        throw new Error("Failed to upload JSON file");
      }
    } catch (error) {
      console.error("Error uploading JSON file:", error);
      alert("An error occurred while uploading the JSON file");
    }
  };

  return (
    <form onSubmit={handleSubmit}>
      <div>
        <input type="file" accept=".json" onChange={handleFileChange} />
      </div>
      <div>
        <button type="submit">Upload JSON File</button>
      </div>
    </form>
  );
};

export default JSONUploadForm;




// pages/YourPage.js
import React from "react";
import JSONUploadForm from "../components/JSONUploadForm";

const YourPage = () => {
  return (
    <div>
      <h1>Upload JSON File</h1>
      <JSONUploadForm />
    </div>
  );
};

export default YourPage;

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.