表单数据和文件数据的报文

1.表单数据和文件数据的报文


* 文件数据


2. 使用new FormData() 上传文件

<form action="http://device.joinstar.cn/api/device/upload" >
        <label for="">
            姓名: <input type="text" name="name">
        </label>
        <label for="">
            文件:<input id="file" type="file" name="file">
        </label>
        <label for="">
            <input type="button" value="保存">
        </label>
  </form>
  <script type="text/javascript">
     var btn = document.querySelector('[type=button]');
btn.onclick = function () {
// 文件元素
var file = document.querySelector('[type=file]');
            console.log('file.files[0]', file.files[0])
// 通过FormData将文件转成二进制数据
var formData = new FormData();
// 将文件转二进制
//*****注意2******
formData.append('upload', file.files[0]);

//*****注意1******
var xhr = new XMLHttpRequest;
xhr.open('post', 'file.php');
// 监听上传进度
xhr.upload.onprogress = function (ev) {
// 事件对象
console.log(ev);


var percent = (ev.loaded / ev.total) * 100 + '%';
console.log(percent);
progress.style.width = percent;
}


xhr.send(formData);
xhr.onreadystatechange = function () {
if(xhr.readyState == 4 && xhr.status == 200) {
//
}
}
}
  </script>

猜你喜欢

转载自blog.csdn.net/qq_38719039/article/details/80189057