Created
September 28, 2020 14:20
-
-
Save Jossdz/3590696f8a293775ebd374b577f15bf9 to your computer and use it in GitHub Desktop.
antd upload
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useState } from "react"; | |
import { Upload, Modal } from "antd"; | |
function UploadPhotos({ setPhotos }) { | |
const [state, setState] = useState({ | |
previewVisible: false, | |
previewImage: "", | |
previewTitle: "", | |
fileList: [], | |
uploaded: [], | |
}); | |
const handleCancel = () => setState({ ...state, previewVisible: false }); | |
function getBase64(file) { | |
return new Promise((resolve, reject) => { | |
const reader = new FileReader(); | |
reader.readAsDataURL(file); | |
reader.onload = () => resolve(reader.result); | |
reader.onerror = (error) => reject(error); | |
}); | |
} | |
const handlePreview = async (file) => { | |
if (!file.url && !file.preview) { | |
file.preview = await getBase64(file.originFileObj); | |
} | |
setState({ | |
...state, | |
previewImage: file.url || file.preview, | |
previewVisible: true, | |
previewTitle: | |
file.name || file.url.substring(file.url.lastIndexOf("/") + 1), | |
}); | |
}; | |
const handleChange = ({ fileList }) => setState({ ...state, fileList }); | |
async function customRequest({ file, onSuccess }) { | |
try { | |
const data = new FormData(); | |
data.append("file", file); | |
data.append("upload_preset", "furniturebank"); | |
const res = await fetch( | |
"https://api.cloudinary.com/v1_1/joss/image/upload", | |
{ | |
method: "POST", | |
body: data, | |
} | |
); | |
const uploadedPicture = await res.json(); | |
setPhotos(uploadedPicture.secure_url); | |
onSuccess(uploadedPicture, file); | |
} catch (err) { | |
throw (err); | |
} | |
} | |
const { previewVisible, previewImage, fileList, previewTitle } = state; | |
const uploadButton = ( | |
<div> | |
<div className="ant-upload-text">Upload photo</div> | |
</div> | |
); | |
return ( | |
<div className="clearfix"> | |
<Upload | |
listType="picture-card" | |
fileList={fileList} | |
onPreview={handlePreview} | |
onChange={handleChange} | |
customRequest={customRequest} | |
> | |
{fileList.length >= 8 ? null : uploadButton} | |
</Upload> | |
<Modal | |
visible={previewVisible} | |
title={previewTitle} | |
footer={null} | |
onCancel={handleCancel} | |
> | |
<img alt="example" style={{ width: "100%" }} src={previewImage} /> | |
</Modal> | |
</div> | |
); | |
} | |
export default UploadPhotos; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment