嘿,又控猪一个

    xiaoxiao2022-07-14  155

    1、手动上传(适用于导入)

    import React from "react"; import ReactDOM from "react-dom"; import "antd/dist/antd.css"; import "./index.css"; import { Upload, Button, Icon, message } from "antd"; // import reqwest from 'reqwest'; import { extend } from "umi-request"; const request = extend({ maxCache: 10, // The maximum number of caches. When it is exceeded, it will automatically clear the first one according to the time. errorHandler: error => { // Centralized processing error } }); class Demo extends React.Component { state = { fileList: [], uploading: false, res: null }; handleUpload = async () => { const { fileList } = this.state; const formData = new FormData(); fileList.forEach(file => { formData.append("files[]", file); }); this.setState({ uploading: true }); const res = await request( "https://www.mocky.io/v2/5cc8019d300000980a055e76", { method: "post", data: formData } ); console.log(res); this.setState({ fileList: [], uploading: false, res: JSON.stringify(res, null, 4) }); // 假设一定会成功,so,不成功就不处理了 message.success("upload successfully."); // You can use any AJAX library you like // reqwest({ // url: '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.'); // }, // }); }; render() { const { uploading, fileList, res } = this.state; const props = { onRemove: file => { this.setState(state => { const index = state.fileList.indexOf(file); const newFileList = state.fileList.slice(); newFileList.splice(index, 1); return { fileList: newFileList }; }); }, beforeUpload: file => { this.setState(state => ({ fileList: [...state.fileList, file] })); return false; }, fileList }; return ( <div> <Upload {...props} listType="picture-card"> <Button> <Icon type="upload" /> Select File </Button> </Upload> <Button type="primary" onClick={this.handleUpload} disabled={fileList.length === 0} loading={uploading} style={{ marginTop: 16 }} > {uploading ? "Uploading" : "Start Upload"} </Button> <div>结果</div> <pre>{res}</pre> </div> ); } } ReactDOM.render(<Demo />, document.getElementById("container"));

    2、手动上传-并转化格式,这种作用不大,一般直接上传就可以了(见3)

    // 字符串转化成数组 export function imgeUrlStr2Array(imageUrl) { if (imageUrl === '' || imageUrl === null || imageUrl === undefined) { return []; } const imageList = imageUrl.split(','); const newImageList = imageList.map((item, index) => { return { url: item, status: 'done', thumbUrl: item, uid: -index, }; }); return newImageList; } import { imgeUrlStr2Array, previewImageFun, } from '@/utils/utils'; import {Col,Row, Form Upload, message} from 'antd'; import {FormComponentProps} from 'antd/lib/form/Form'; import {connect} from 'dva'; import * as React from 'react'; const FormItem = Form.Item; const {TextArea} = Input; const {Option} = Select; interface Props { visible?: boolean; baseInfo?: any; onCancel?: () => void; onOk?: (value:any) => void; dispatch?: any; user?: any; qualificationQuery?: any; } @connect(state => ({ user: state.user, })) class QueryOtherForm extends React.PureComponent<Props & FormComponentProps, any> { state = { fileList: this.props.baseInfo.imageList ? [...this.props.baseInfo.imageList] : [], }; componentDidMount() { this.getList(); } handleOk = async () => { const headPortrait = await this.handleUpload2() const {form,onOk} =this.props form.validateFields((errors, values) => { if (errors) { return; } // const headPortrait = values.headPortrait.map(item => { // if (item.response) { // // 是新上传 // return (item.response.data && item.response.data.imageUrl) || ''; // } // // 非新上传 // return item.url; // // }); const params = { ...values, workBeginsCreate: values.workBeginsCreate ? `${moment(values.workBeginsCreate).format(dateFormat) } 00:00:00` : '', headPortrait, // headPortrait: headPortrait.join(','), }; onOk(params); }) }; handleUpload2 = async () => { const { fileList } = this.state; const formData = new FormData(); fileList.forEach(file => { formData.append('files', file); }); this.setState({ uploading: true, }); const { dispatch } = this.props; const res = await dispatch({ type: 'user/upload', payload: formData, }); const url =res.data.imageUrl console.log(url) await this.setState({ uploading: false, fileList:imgeUrlStr2Array(url) }); console.log('this.fileList',this.state.fileList) message.success('upload successfully.'); return url }; // 预览 handlePreview = file => { // this.setState({ // previewImage: file.url || file.thumbUrl, // previewVisible: true, // }); previewImageFun(file); }; render() { const {fileList} = this.state; const formItemLayout = { labelCol: { xs: {span: 24}, sm: {span: 6} }, wrapperCol: { xs: {span: 24}, sm: {span: 18} } }; const props = { onRemove: file => { this.setState(state => { const index = state.fileList.indexOf(file); const newFileList = state.fileList.slice(); newFileList.splice(index, 1); return { fileList: newFileList, }; }); }, beforeUpload: file => { this.setState(state => ({ fileList: [...state.fileList, file], })); return false; }, fileList, }; const uploadButton = ( <div> <Icon type="plus" /> <div className="ant-upload-text">上传头像</div> </div> ); return ( <Form> <Row> <Col span={8}> <Upload {...props} fileList={fileList} listType="picture-card"> {fileList.length >= 1 ? null : uploadButton} </Upload> </Col> </Row> </Form> ); } }

    3、直接上传,立即返回结果

    export const UPLOAD_URL = `${getServerPath()}/server/web/upload/register`; normFile = e => { if (Array.isArray(e)) { return e; } this.setState({ fileList: e.fileList }); return e && e.fileList; }; <FormItem {...formItemLayout} style={{marginBottom: 0}} label="照片"> {getFieldDecorator('headPortrait', { valuePropName: 'headPortrait', getValueFromEvent: this.normFile, initialValue: fileList, })( <Upload withCredentials accept="image/*" name="files" action={UPLOAD_URL} listType="picture-card" fileList={fileList} > {fileList.length >= 1 ? null : uploadButton} </Upload> )} </FormItem>
    最新回复(0)