ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

上传文件

2020-10-21 18:02:49  阅读:161  来源: 互联网

标签:文件 const name res file 上传 response wx


小程序上传文件
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={{ width: 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();
                            }
                        });
                    }
                }
            });
        },

标签:文件,const,name,res,file,上传,response,wx
来源: https://www.cnblogs.com/zppsakura/p/13853857.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有