您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
这篇文章将为大家详细讲解有关如何实现基于React-Dropzone开发上传组件功能,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。
1. axios上传普通文件:
通过yarn将react-dropzone和引入:
yarn add react-dropzone axios
前端js如下(如有缺失,请自行修改):
import React, { useState, useCallback, useEffect, } from 'react'; import {useDropzone} from 'react-dropzone'; import "./dropzone.styles.css" import InfiniteScroll from 'react-infinite-scroller'; import { List, message, // Avatar, Spin, } from 'antd'; import axios from 'axios'; /** * 计算文件大小 * @param {*} bytes * @param {*} decimals * @returns */ function formatBytes(bytes, decimals = 2) { if (bytes === 0) return '0 Bytes'; const k = 1024; const dm = decimals < 0 ? 0 : decimals; const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']; const i = Math.floor(Math.log(bytes) / Math.log(k)); return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i]; } /** * Dropzone 上传文件 * @param {*} props * @returns */ function DropzoneUpload(props) { const [files, setFiles] = useState([]) const [loading, setLoading] = useState(false); const [hasMore, setHasMore] = useState(true); const onDrop = useCallback(acceptedFiles => { setLoading(true); const formData = new FormData(); smallFiles.forEach(file => { formData.append("files", file); }); axios({ method: 'POST', url: '/api/files/multiplefiles', data: formData, headers: { "Content-Type": "multipart/form-data", } }) then(resp => { addFiles(acceptedFiles); setLoading(false); }); }, [files]); // Dropzone setting const { getRootProps, getInputProps } = useDropzone({ multiple:true, onDrop, }); // 删除附件 const removeFile = file => { const newFiles = [...files] newFiles.splice(newFiles.indexOf(file), 1) setFiles(newFiles) } useEffect(() => { // init uploader files setFiles([]) },[]) return ( <section className="container"> <div {...getRootProps({className: 'dropzone'})}> <input {...getInputProps()} /> <p>拖动文件或点击选择文件?</p> </div> <div className="demo-infinite-container"> <InfiniteScroll initialLoad={false} pageStart={0} loadMore={handleInfiniteOnLoad} hasMore={!loading && hasMore} useWindow= {false} > <List dataSource={files} renderItem={item=> ( <List.Item actions={[ // <a key="list-loadmore-edit">编辑</a>, <a key="list-loadmore-delete" onClick={removeFile}>删除</a> ]} // extra={ // } key={item.path}> <List.Item.Meta avatar={ <> { !!item.type && ['image/gif', 'image/jpeg', 'image/png'].includes(item.type) && <img width={100} alt='logo' src={item.preview} /> } </> } title={item.path} description={formatBytes(item.size)} /> </List.Item> )} > {loading && hasMore && ( <div className="demo-loading-container"> <Spin /> </div> )} </List> </InfiniteScroll> </div> </section> ); }
flask代码:
def multiplefiles(): if 'files' not in request.files: return jsonify({'message': '没有文件!'}), 200 files = request.files.getlist('files') for file in files: if file: # 通过拼音解决secure_filename中文问题 filename = secure_filename(''.join(lazy_pinyin(file.filename)) Path(UPLOAD_FOLDER + '/' + file_info['dir_path']).mkdir(parents=True, exist_ok=True) file.save(os.path.join(UPLOAD_FOLDER + '/' + file_info['dir_path'], filename)) return jsonify({'message': '保存成功!!'})
2. 大文件导入:
通过file.slice()方法生成文件的chunks。不要用Promise.all容易产生非顺序型的请求,导致文件损坏。
js代码:
const promiseArray = largeFiles.map(file => new Promise((resolve, reject) => { const chunkSize = CHUNK_SIZE; const chunks = Math.ceil(file.size / chunkSize); let chunk = 0; let chunkArray = new Array(); while (chunk <= chunks) { let offset = chunk * chunkSize; let slice = file.slice(offset, offset+chunkSize) chunkArray.push([slice, offset]) ++chunk; } const chunkUploadPromises = (slice, offset) => { const largeFileData = new FormData(); largeFileData.append('largeFileData', slice) return new Promise((resolve, reject) => { axios({ method: 'POST', url: '/api/files/largefile', data: largeFileData, headers: { "Content-Type": "multipart/form-data" } }) .then(resp => { console.log(resp); resolve(resp); }) .catch(err => { reject(err); }) }) }; chunkArray.reduce( (previousPromise, [nextChunk, nextOffset]) => { return previousPromise.then(() => { return chunkUploadPromises(nextChunk, nextOffset); }); }, Promise.resolve()); resolve(); }))
flask代码:
filename = secure_filename(''.join(lazy_pinyin(filename))) Path(UPLOAD_FOLDER + '/' + file_info['dir_path']).mkdir(parents=True, exist_ok=True) save_path = os.path.join(UPLOAD_FOLDER + '/' + file_info['dir_path'], filename) try: with open(save_path, 'ab') as f: f.seek(offset) f.write(file.stream.read()) print("time: "+ str(datetime.now())+" offset: " + str(offset)) except OSError: return jsonify({'Could not write to file'}), 500
关于“如何实现基于React-Dropzone开发上传组件功能”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。