Advertisement
raffaelegriecoit

Untitled

Aug 10th, 2024
281
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import React, { useState } from 'react';
  2. import axios from 'axios';
  3.  
  4. function UploadImages({ structureId }) {
  5.     const [images, setImages] = useState([]);
  6.     const [uploadStatus, setUploadStatus] = useState(null);
  7.  
  8.     const handleImageChange = (e) => {
  9.         setImages(e.target.files);
  10.     };
  11.  
  12.     const handleSubmit = async (e) => {
  13.         e.preventDefault();
  14.         if (images.length === 0) {
  15.             setUploadStatus("Please select images to upload.");
  16.             return;
  17.         }
  18.  
  19.         const formData = new FormData();
  20.         for (let i = 0; i < images.length; i++) {
  21.             formData.append('images', images[i]);
  22.         }
  23.  
  24.         try {
  25.             const response = await axios.post(`/api/structure/${structureId}/add-images/`, formData, {
  26.                 headers: {
  27.                     'Content-Type': 'multipart/form-data',
  28.                     'Authorization': `Token ${localStorage.getItem('token')}` // assuming token is stored in localStorage
  29.                 }
  30.             });
  31.             setUploadStatus("Images uploaded successfully.");
  32.             console.log(response.data);
  33.         } catch (error) {
  34.             setUploadStatus("Failed to upload images. " + error.message);
  35.         }
  36.     };
  37.  
  38.     return (
  39.         <div>
  40.             <form onSubmit={handleSubmit}>
  41.                 <input type="file" multiple onChange={handleImageChange} />
  42.                 <button type="submit">Upload Images</button>
  43.             </form>
  44.             {uploadStatus && <p>{uploadStatus}</p>}
  45.         </div>
  46.     );
  47. }
  48.  
  49. export default UploadImages;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement