• 上传文件


    小程序上传文件
    chooseFile(e){
                var that = this;
                wx.chooseMessageFile({ 
                    count: 10,
                    type: 'file',
                    success (res) {
                        const tempFilePaths = res.tempFiles[0];
                        wx.showLoading({
                            mask: true,
                            title: '加载中...'
                        });
                        wx.uploadFile({
                            url: 'https://cp-api.zhgcloud.com/weapp/files',
                            header: {
                                'Content-Type': 'multipart/form-data',
                                Cookie: wepy.getStorageSync(COOKIE)
                            },
                            filePath: tempFilePaths.path,
                            formData: {
                                fileName: tempFilePaths.name
                            },
                            name: 'upload_file',
                            success(res) {
                                wx.hideLoading();
                                const response = JSON.parse(res.data);
                                if (response.XCmdrCode !== 0) {
                                    return wx.showToast({
                                        title: '上传附件失败',
                                        icon: 'none'
                                    });
                                }
                                that.extensionFiles.push(response.XCmdrResult);
                                that.machines.attachments_file_ids.push(response.XCmdrResult.id);
                                that.$apply();
                            }
                        })
                    }    
                })
            },
    
    小程序上传图片
    chooseImage(type, index) {
                app.globalData.hasChooseImage = true;
                wx.chooseImage({
                    count: 1,
                    sizeType: ['compressed'],
                    sourceType: ['album', 'camera'],
                    success: (res) => {
                        let tempFilePaths = res.tempFilePaths;
                        wx.uploadFile({
                            url: 'https://cp-wx.zhgcloud.com/images',
                            header: {
                                'Content-Type': 'multipart/form-data',
                                Cookie: wepy.getStorageSync(COOKIE)
                            },
                            filePath: tempFilePaths[0],
                            name: 'machine_image',
                            success: (res) => {
                                const response = JSON.parse(res.data);
                                if (response.XCmdrCode !== 0) {
                                    return wx.showToast({
                                        title: '上传图片失败',
                                        icon: 'none'
                                    });
                                }
                                this.machines.images.push(response.XCmdrResult.path);
                                this.extensionImage.push(response.XCmdrResult.url);
                                this.$apply();
                            }
                        });
                    },
                    complete: () => {
                        app.globalData.hasChooseImage = false;
                    }
                });
            },
    
    Antd上传图片
    #uploadProps参数
    
    const uploadProps = {
        action: `${apiHostMap.CP_HOST_WEB}/images`,
        headers: { 'X-Requested-With': null },
        withCredentials: true,
        name: 'machine_image',
        accept: 'image/jpg,image/jpeg,image/png',
        beforeUpload: file => {
        	if (
        		!(
                    file.type === 'image/jpeg' ||
                    file.type === 'image/jpg' ||
                    file.type === 'image/png'
                )
    		) {
                Modal.warning({
                maskClosable: true,
                content: '图片格式须为 png、jpg!',
            });
    		return false;
    		}
            if (file.size > maxSingleImageSize * m) {
            	Modal.warning({
           		 	maskClosable: true,
           			content: `单个图片大小不能超过 				   ${maxSingleImageSize}M!`,
            });
            return false;
            }
            },
            showUploadList: { showDownloadIcon: false },
            };
            
     #定义的uploadButton
    const uploadButton = (
                <div className={style.uploadBox}>
                    <Icon type="plus" className={style.uploadIcon} />
                    <div className={style.uploadText}>上传图片</div>
                </div>
            );
    
    
    #Upload 组件
    <Upload
    {...uploadProps}
    listType="picture-card"
    fileList={infoImages}
    onChange={({ fileList }) => {
    	const { dispatch } = this.props;
        dispatch({
            type: 'machineDetail/overrideStateProps',
            payload: {
                infoImages: fileList,
            },
        });
    }}
    onPreview={this.handlePreview}
    >
    {infoImages.length >= 5 ? null : uploadButton}
    </Upload>
    

    注:fileList={infoImages}中的infoImages对象中必须包含uid,否则报错 若后端未返回,可在获取数据时手动添加上

    如:

    if (images.length > 0) {
                        images.forEach(img => {
                            img.uid = img.url;
                        });
                    }
    
    Antd上传附件
    #props
    const maxSingleFileSize = 8;
    const m = 1024 * 1024;
    const props = {
        name: 'upload_file',
        multiple: true,
        withCredentials: true,
        data: {
            source_type: 'contract',
        },
        beforeUpload: file => {
            const fileType = [
                'jpg',
                'jpeg',
                'png',
                'doc',
                'docx',
                'xls',
                'xlsx',
                'ppt',
                'pptx',
                'wps',
                'et',
                'dps',
                'pdf',
                'txt',
            ];
            // 文件显示
            return new Promise((resolve, reject) => {
                const type = file.name.substr(file.name.lastIndexOf('.') + 1).toLowerCase();
                if (fileType.indexOf(type) === -1) {
                    Modal.warning({
                        maskClosable: true,
                        title: '文件须为word、excel、ppt、pdf、txt、图片!',
                    });
                    reject(file);
                } else if (file.size > maxSingleFileSize * m) {
                    Modal.warning({
                        maskClosable: true,
                        title: `单个文件大小不能超过${maxSingleFileSize}M!`,
                    });
                    reject(file);
                } else {
                    resolve(file);
                }
            });
        },
        action: `${apiHostMap.CP_HOST_WEB}/files`,
    };
    
    
    #onChanges
    onChanges(info) {
            const { file } = info;
            const { response, status, name } = file;
            let id = '';
            if (response?.XCmdrResult) {
                id = response.XCmdrResult.id;
            }
            const { infoAttachments } = this.props.machineDetail;
            const list = infoAttachments;
            if (status === 'done' && id) {
                if (list.length > 7) {
                    message.error('最多可上传8张附件');
                } else {
                    list.push({ id, name });
                    this.props.dispatch({
                        type: 'machineDetail/overrideStateProps',
                        payload: {
                            infoAttachments: list,
                        },
                    });
                }
            } else if (status === 'error') {
                message.error(`${info.file.name} file upload failed.`);
            }
        }
    
    
    <Dragger
        {...props}
        defaultFileList={list}
        onChange={e => this.onChanges(e)}
        style={{  384, padding: 22, margin: '0 24px' }}
        showUploadList={false}
    >
        <p className="ant-upload-drag-icon">
        <Icon type="inbox" />
        </p>
        <p className="ant-upload-text">点击或将文件拖拽到这里上传</p>
    	<p className="ant-upload-hint">支持扩展名:.doc .docx .pdf .jpg...</p>
    </Dragger>
    
    小程序查看附件或图片
    download(file) {
                wx.showLoading({
                    mask: true,
                    title: '加载中...'
                });
                const list = ['jpg', 'jpeg', 'png'];
                const url = `https://d-dev.zhgcloud.com/file/${file.path}`;
                wx.downloadFile({
                    url: url,
                    success: function(res) {
                        var filePath = res.tempFilePath;
                        var index1 = filePath.lastIndexOf('.');
                        var index2 = filePath.length;
                        var postf = filePath.substring(index1, index2);// 后缀名
                        var postf1 = postf.replace(/./g, '');
                        if (list.includes(postf1)) {
                            wx.previewImage({
                                current: url,
                                urls: [url],
                                success: function(res) {
                                    wx.hideLoading();
                                }
                            });
                        } else {
                            wx.openDocument({
                                filePath: filePath,
                                fileType: postf1,
                                success: function(res) {
                                    wx.hideLoading();
                                }
                            });
                        }
                    }
                });
            },
    
  • 相关阅读:
    uinty之碰撞体,触碰体,刚体
    背景图片的设置和定位等
    margin padding
    《大道至简》之懒人的‘懒’
    灭霸—个人冲刺2(1)
    软件工程—个人作业(7.2)
    软件工程—个人作业(7.1)
    学习进度(13)
    学习进度(12)
    人月神话阅读笔记02
  • 原文地址:https://www.cnblogs.com/zpsakura/p/13853857.html
Copyright © 2020-2023  润新知