迁久尘 2023-12-24 11:07 采纳率: 66.7%
浏览 7
已结题

上传文件原生的ajax应改怎么写

这是$ajax的写法

img

那类似这样的怎么写,网上实在是找不到了,那类似这样的怎么写,网上实在是找不到了

img

  • 写回答

2条回答 默认 最新

  • 是悟能了 前端领域优质创作者 2023-12-25 10:58
    关注

    拿走不用客气

    function uploadFile(url, file, onProgress, onSuccess, onError) {
      const xhr = new XMLHttpRequest();
      const formData = new FormData();
    
      formData.append('file', file);
    
      xhr.open('POST', url, true);
    
      xhr.upload.onprogress = function(event) {
        if (event.lengthComputable) {
          const percentComplete = event.loaded / event.total * 100;
          onProgress(percentComplete);
        }
      };
    
      xhr.onload = function() {
        if (xhr.status >= 200 && xhr.status < 300) {
          onSuccess(xhr.responseText);
        } else {
          onError(new Error('Upload failed with status ' + xhr.statusText));
        }
      };
    
      xhr.onerror = function() {
        onError(new Error('Upload failed with status ' + xhr.statusText));
      };
    
      xhr.send(formData);
    }
    
    // 使用方法
    const fileInput = document.querySelector('input[type="file"]');
    fileInput.addEventListener('change', function(event) {
      const file = event.target.files[0];
      uploadFile(
        '/upload', 
        file, 
        function(progress) {
          console.log('Upload progress: ' + progress + '%');
        },
        function(responseText) {
          console.log('Upload complete: ' + responseText);
        },
        function(error) {
          console.error('Upload failed: ' + error.message);
        }
      );
    });
    
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 1月2日
  • 已采纳回答 12月25日
  • 创建了问题 12月24日

悬赏问题

  • ¥15 通联支付网上收银统一下单接口
  • ¥15 angular有偿编写,
  • ¥15 centos7系统下abinit安装时make出错
  • ¥15 hbuildex运行微信小程序报错
  • ¥15 关于#python#的问题:我知道这个问题对你们来说肯定so easy
  • ¥15 wpf datagrid如何实现多层表头
  • ¥15 为啥画版图在Run DRC会出现Connect Error?可我Calibre的hostname和计算机的hostname已经设置成一样的了。
  • ¥20 网站后台使用极速模式非常的卡
  • ¥20 Keil uVision5创建project没反应
  • ¥15 mmseqs内存报错