-
Notifications
You must be signed in to change notification settings - Fork 241
/
Copy pathupload.js
95 lines (81 loc) · 2.43 KB
/
upload.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import React, { useState } from 'react';
import AWS from 'aws-sdk';
import Swal from 'sweetalert2';
const UploadImage = () => {
const [selectedFile, setSelectedFile] = useState(null);
const handleFileInput = (e) => {
setSelectedFile(e.target.files[0]);
};
const handleUpload = () => {
AWS.config.update({
accessKeyId: '',
secretAccessKey: '',
region: '',
});
const s3 = new AWS.S3();
const fileName = selectedFile.name;
const fileType = selectedFile.type;
const bucketName = '';
const objectKey = `${Date.now()}-${fileName}`;
const params = {
Bucket: bucketName,
Key: objectKey,
Body: selectedFile,
ContentType: fileType,
ACL: 'public-read',
};
s3.upload(params, (err, data) => {
if (err) {
console.log('Error uploading image: ', err);
} else {
console.log('Image uploaded successfully: ', data.Location);
Swal.fire({
icon: 'success',
title: 'Image uploaded successfully',
text: data.Location,
});
setSelectedFile(null);
}
});
};
return (
<div className="max-w-lg mx-auto my-8">
<div className="flex flex-col items-center justify-center border-4 border-dashed border-gray-400 h-64 w-full rounded-lg">
{selectedFile ? (
<img
className="object-contain h-48 rounded-md"
src={URL.createObjectURL(selectedFile)}
alt="Selected file preview"
/>
) : (
<div className="text-center">
<p className="mb-2">Drag and drop an image here or click to select</p>
<input
type="file"
className="hidden"
onChange={handleFileInput}
accept=".jpg,.jpeg,.png"
/>
<button
className="px-4 py-2 text-white bg-blue-500 rounded-md hover:bg-blue-600"
onClick={() => document.querySelector('input[type="file"]').click()}
>
Select Image
</button>
</div>
)}
</div>
{selectedFile && (
<div className="text-center mt-4">
<button
className="px-4 py-2 text-white bg-green-500 rounded-md hover:bg-green-600"
onClick={handleUpload}
>
Upload Image
</button>
</div>
)}
</div>
);
};
export default UploadImage;