FileReader.readAsDataURL()
1.使用antd中的upload組件進行實現
{ avatarVisible && <Modal title="上傳頭像" visible={avatarVisible} onOk={this.onUpload} onCancel={this.onCancel} className={styles.modalBox} bodyStyle={{ height: 500 }} > <Upload name="avatar" listType="picture-card" className="avatar-uploader" showUploadList={false} beforeUpload={this.beforeUpload} > <Button> 選擇圖片 </Button> </Upload> <Row> <Col span={12}> <span> 支持JPG、GIF、PNG格式,小於2M </span> <div className={styles.leftContainer}> {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : null} </div> </Col> <Col span={12}> <span>效果預覽</span> <div className={styles.previewContainer}> {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : null} </div> </Col> </Row> </Modal>
}
主要運用了beforeUpload方法,上傳之前先獲取file的屬性並進行解析渲染
// 解析為base64位 getBase64 = (img, callback) => { const reader = new FileReader(); reader.addEventListener('load', () => callback(reader.result));
// 讀取文件 reader.readAsDataURL(img); } // 上傳之前 beforeUpload = file => { const { fileList } = this.state; this.getBase64(file, imageUrl => this.setState({ imageUrl, fileList: [...fileList, file], // loading: false, }), ); return false; }
再利用ajax請求,進行上傳
onUpload = () => { const { fileList } = this.state; const formData = new FormData(); fileList.forEach(file => { formData.append('files[]', file); }); this.setState({ // uploading: true, }); // You can use any AJAX library you like request('https://www.mocky.io/v2/5cc8019d300000980a055e76', { method: 'post', processData: false, data: formData, success: () => { this.setState({ fileList: [], // uploading: false, }); message.success('upload successfully.'); }, error: () => { this.setState({ // uploading: false, }); message.error('upload failed.'); }, }); };
2.使用js進行實現
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>單圖片上傳預覽</title> </head> <body> <div align="center"> <img width="400" height="250" id="xmTanImg"/><br/> <input type="file" id="pic" name="pic" onchange="xmTanUploadImg(this)"/> <input type="button" value="上傳圖片"/><br /> </div> <script> //選擇圖片,馬上預覽 function xmTanUploadImg(obj) { var file = obj.files[0]; //file.size 單位為byte 可以做上傳大小控制 console.log("file.size = " + file.size); var reader = new FileReader(); //讀取文件過程方法 reader.onloadstart = function (e) { console.log("開始讀取...."); } reader.onprogress = function (e) { console.log("正在讀取中...."); } reader.onabort = function (e) { console.log("中斷讀取...."); } reader.onerror = function (e) { console.log("讀取異常...."); } reader.onload = function (e) { console.log("成功讀取...."); var img = document.getElementById("xmTanImg"); img.src = e.target.result; //或者 img.src = this.result; //e.target == this } reader.readAsDataURL(file) } </script> </body> </html>