文章目录
  1. 1. 方式1
  2. 2. 方式2

方式1

1
2
3
4
5
6
<form id="formAudio" method="post" enctype="multipart/form-data" name="formAudio" target="rfFrame"> 
<input type="file" name='uploadFile' @change="onChange_file">
<input type="submit" name="submit" id="submit">
<input type="reset" name="submit" id="reset" >
</form>
<iframe name="rfFrame" style="display:none;"></iframe>

form提交之后会刷新页面,追加个iframe隐藏掉,然后把formtarget设为iframename,这样form刷新的就是iframe.

提交都服务端

1
2
3
document.getElementById('formAudio').action = apiPath;
document.getElementById('submit').click();
document.getElementById('reset').click();

方式2

动态创建<form>,并通过append方法为其附加<input>的值

1
2
3
4
let formData = new FormData();
formData.append('file','音频文件');
//可以通过get()方法获取方才追加的值
formData.get('file');

重点来了,怎么发送给服务端呢?
使用XHR发送file或者Blob.注意所有file都是Blob,所以在此使用2者都可以.

//创建xhr对象
let xhr = new XMLHttpRequest();
//设置xhr请求超时时间
xhr.timeout = 3000;
//设置相应返回的数据格式
xhr.responseType = 'json';
//允许跨域请求
xhr.withCredentials = true;
//创建一个post 请求,采用异步.
xhr.open('POST',apiPath,true);

xhr.ontimeout = function (){//请求超时}
xhr.onload = function () {//上传成功,不需要返回的数据,这个事件也可以作为回调}
//每当readState 改变时,就会触发该事件
//readState(0-4)状态值
xhr.onreadystatechange  = function (){
    if(xhr.readState == 4){
        if(xhr.status >= 200 && xhr.status < 300){
            if(xhr.response && xhr.response.data)
            {//上传成功,服务端返回的数据
            }
        }
    }

//发送数据
xhr.send(formData)//表单数据默认Content-Type 为 multipart/form-data
文章目录
  1. 1. 方式1
  2. 2. 方式2