使用js写一个多文件上传的组件

// UploadComponent.jsx
import React, { useState } from 'react';

const UploadComponent = ({ onUpload }) => {
  const [selectedFiles, setSelectedFiles] = useState([]);

  const handleFileChange = (e) => {
    setSelectedFiles(Array.from(e.target.files));
  };

  const handleUpload = async () => {
    if (!selectedFiles.length) {
      alert('Please select files to upload.');
      return;
    }

    const formData = new FormData();
    selectedFiles.forEach((file) => {
      formData.append('files', file);
    });

    try {
      const response = await fetch('/upload', { // Replace '/upload' with your backend endpoint
        method: 'POST',
        body: formData,
      });

      if (response.ok) {
        const data = await response.json();
        onUpload(data); // Callback to handle successful upload
        setSelectedFiles([]); // Clear selected files after upload
      } else {
        console.error('Upload failed:', response.status, response.statusText);
        alert('Upload failed. Please try again.');
      }
    } catch (error) {
      console.error('Upload error:', error);
      alert('An error occurred during upload.');
    }
  };

  return (
    <div>
      <input type="file" multiple onChange={handleFileChange} />
      <button onClick={handleUpload} disabled={!selectedFiles.length}>
        Upload
      </button>
      {selectedFiles.length > 0 && (
        <ul>
          {selectedFiles.map((file, index) => (
            <li key={index}>{file.name}</li>
          ))}
        </ul>
      )}
    </div>
  );
};

export default UploadComponent;


// App.jsx (Example usage)
import React, { useState } from 'react';
import UploadComponent from './UploadComponent';

const App = () => {
  const [uploadedFiles, setUploadedFiles] = useState([]);

  const handleUpload = (data) => {
    console.log('Files uploaded successfully:', data);
    setUploadedFiles(data); // Update the state with uploaded file information
  };

  return (
    <div>
      <UploadComponent onUpload={handleUpload} />
      {uploadedFiles.length > 0 && (
        <div>
          <h2>Uploaded Files:</h2>
          <ul>
            {uploadedFiles.map((file, index) => (
              <li key={index}>{file.name} - {file.size} bytes</li> // Display file information
            ))}
          </ul>
        </div>
      )}
    </div>
  );
};

export default App;

Key improvements and explanations:

  • Clearer file selection display: Shows the names of selected files in a list.
  • Disabled upload button: Prevents upload attempts when no files are selected.
  • Error handling: Includes try...catch blocks and displays informative error messages to the user.
  • Success callback: The onUpload prop allows the parent component to handle successful uploads and update its state accordingly. This example shows how to update a list of uploaded files.
  • Clearing selected files: Clears the file input after a successful upload.
  • Example usage in App.jsx: Demonstrates how to use the UploadComponent and handle the onUpload callback. This example shows how uploaded file information (like filename and size) could be handled and displayed.
  • Comments: Added comments to explain the code's functionality.

Backend Considerations (Node.js with Express example):

You'll need a backend to handle the actual file uploads. Here's a basic example using Node.js with Express and multer:

const express = require('express');
const multer = require('multer');
const app = express();
const upload = multer({ dest: 'uploads/' }); // Set your upload directory

app.use(express.json());

app.post('/upload', upload.array('files'), (req, res) => {
  try {
    const uploadedFiles = req.files.map(file => ({
      name: file.originalname,
      size: file.size,
      // ... other file information you want to send back
    }));
    res.json(uploadedFiles);
  } catch (error) {
    console.error('Error uploading files:', error);
    res.status(500
posted @ 2024-12-10 06:15  王铁柱6  阅读(64)  评论(0)    收藏  举报