设为首页 加入收藏

TOP

一文了解H5照片上传过程(二)
2019-09-17 19:10:09 】 浏览:102
Tags:一文 了解 照片 上传 过程
h.min(img.width, 200);//控制图片大小 const radio = canvas.width / img.width; canvas.height = img.height * radio; //等比缩放 ctx.drawImage(img, 0, 0, canvas.width, canvas.height); const quality = 0.8; //控制输出图片质量 canvas.toBlob(file => { let files = new window.File([file], 'file.jpg', { type: file.type }); resolve(files); }, 'image/jpeg', quality); }; }); },

这里有个要注意的点,toBlob之后是一个Blob对象,但是请求要求传入file文件,所以我们要将blob对象转为file

    let files = new window.File([this.blob], file.name, {type: file.type})

五、图片上传

通过FormData创建表单数据,发起 ajax POST请求即可,下面函数实现了上传文件。

// 上传图片
        uploadFile(file) {
            return request({
                method: 'post',
                postType: 'file',
                url: '//...域名.../upload/comments',
                data: {
                    file: file
                }
            });
        },
export function formData(obj) {
    let formData = new FormData();

    Object.keys(obj).forEach(key => {
        let val = obj[key];
        val = val == null ? '' : val;
        if (typeof val === 'object') {
            if (val instanceof window.File) {
                formData.append(key, val);
            } else {
                formData.append(key, JSON.stringify(val));
            }
        } else {
            formData.append(key, val);
        }
    });
    return formData;
}
export function request(options) {
    return new Promise((resolve, reject) => {
        let {
            method,
            url,
            data,
            params,
            headers = {},
            withCredentials = false,
            // file || ''
            postType = ''
        } = options;

        const xhr = new XMLHttpRequest();
        let sendData = null;
        method = (method || 'GET').toUpperCase();

        const urlParse = /\?/.test(url) ? parseString(url) : {};
        const querys = { timestamp: Math.round(new Date() / 1000), app_id: values.app_id, ...urlParse, ...params };

        // 验签
        let keys = Object.keys(querys);
        keys.push('app_secret');
        const api_sign = sha1(keys.sort().map(key => querys[key] || values[key]).join(''));

        // console.log('api_sign', api_sign);

        headers.api_sign = api_sign;

        url +=
        (/\?/.test(url) ? '&' : '?') +
        Object.keys(querys)
            .map(key => `${key}=${escape(querys[key])}`)
            .join('&');

        xhr.open(method, url, true);

        // 处理sendData
        // postType file
        if (method === 'POST') {
            if (postType === 'file') {
                sendData = data ? formData(data) : null;
            } else {
                headers['Content-Type'] = headers['Content-Type'] || 'application/json;charset=UTF-8';
                sendData = data ? JSON.stringify(data) : null;
            }
        }

        Object.keys(headers).forEach(key => {
            xhr.setRequestHeader(key, headers[key]);
        });

        xhr.onreadystatechange = function() {
            if (xhr.readyState === 4 && xhr.status === 200) {
                // options.success(xhr.responseText);
                let response = {
                    status: xhr.status,
                    data: {}
                };
                try {
                    response.data = JSON.parse(xhr.responseText);
                } catch (e) {
                    console.warn('request error:', e);
                }

                if (response) {
                    resolve(response);
                } else {
                    reject(new Error('cancel by response interceptor'));
                }
            }
        };
        xhr.onerror = reject;

        // withCredentials默认为true
        xhr.withCredentials = withCredentials;

        // console.log(url, headers, sendData);
        xhr.send(sendData);
    });
}

 六、合并上传

onFileChange(e) {
            const files = Array.prototype.slice.call(e.target.files);
            files.forEach(file => {
                // 本地预览
                // let url=window.URL.createObjectURL(file)
                // this.photo.push(url)
                this.compressImage(file)
                    .then(file => {
                        return this.uploadFile(file);
                    }).then(data => {
                        let goodsImage = data.data.data;
                        this.goods.
首页 上一页 1 2 3 下一页 尾页 2/3/3
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇jQuery设置样式css 下一篇JavaScript 弹出框

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目