js以formdata的形式上传文件

以上传图片为例:

在html中我们这么写:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <form id="fileform" enctype="multipart/form-data">
        <input type='file' name='file'/><br/>
        <input type='submit' value='submit'/>
    </form>
</body>
<script src="https://code.jquery.com/jquery-3.7.1.min.js"  type="text/javascript"></script>
<script>
     /*上传文件*/
     document.querySelector("#fileform").addEventListener("submit", function(event) {
                var formdata=new FormData($("#fileform")[0]);
              
                $.ajax({
                    type : 'post',
                    url :host+'/file/uploadFileLocal?xxxxxxxxxxxxxx',//地址改为后台给的上传地址
                    data : formdata,
                    cache : false,
                    processData : false, // 不处理发送的数据,因为data值是Formdata对象,不需要对数据做处理
                    contentType :false, // 不设置Content-type请求头
                    success : function(res){
                    //上传成功
                     },
                    error : function(x){
                    //上传失败
                    }
                })
                event.preventDefault();
            })
</script>
</html>

那么在框架中频繁使用,给直接给它封装好,下面可以直接复制使用:

export const upload=(option)=>{
    const xhr = new XMLHttpRequest();//定义上传方式

    if (option.onProgress && xhr.upload) {
        xhr.upload.onprogress = function progress(e) {
            if (e.total > 0) {
                e.percent = e.loaded / e.total * 100;
            }
            option.onProgress(e);//上传进度,也是上传成功后回调
        };
    }

    const formData = new FormData();
    formData.append('file', option.file,option.file.name);


    xhr.onerror = function error(e) {
        option.onError(e);//失败返回
    };
    xhr.onload = function onload() {
        if (xhr.status < 200 || xhr.status >= 300) {
            return option.onError(getError(option, xhr), getBody(xhr));
        }
        option.onSuccess(getBody(xhr), xhr);//成功返回函数
    };

    
    xhr.open('post', option.action, true);

    if (option.withCredentials && 'withCredentials' in xhr) {
        xhr.withCredentials = true;
    }

    const headers = option.headers || {};//定义请求头
    if (headers['X-Requested-With'] !== null) {
        xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
    }
    for (const h in headers) {
        if (headers.hasOwnProperty(h) && headers[h] !== null) {
            xhr.setRequestHeader(h, headers[h]);
        }
    }


    xhr.send(formData);

    return {
        abort() {
            xhr.abort();
        },
    };
};
export default upload;

使用方式:

   upload({ 
        file: options.file, 
        filename: options.file.name, //文件名称
        headers: {
        //header对象
        }, 
        action:'',//上传文件的地址
        onError(e){
        //失败了
        },onSuccess(e){
          //成功了

        }
    })

上传格式预览:

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值