代码之家  ›  专栏  ›  技术社区  ›  DeputyDong_

xmlHTTP POST请求

  •  0
  • DeputyDong_  · 技术社区  · 7 年前

    我查看了stackoverflow和google,但到目前为止还没有找到有效的解决方案。

    https://ptsv2.com/ 测试上传。

    这是我的代码:

    var url = "https://corsanywhere.herokuapp.com/https://ptsv2.com/t/zuaco-1549007477/post";      
    
    var base64Credentials = btoa(username+":"+password);
    
    var xhttp = new XMLHttpRequest();
              var fd = new FormData();
              /* Add the file */ 
              fd.append("file", "img/1.png");
    
    xhttp.open("POST", url, true);
    xhttp.setRequestHeader("Authorization", "Basic " + base64Credentials);
    xhttp.setRequestHeader("Content-Type", "image/png");
    xhttp.send(fd);
    
       /* Check the response status */  
       xhttp.onreadystatechange = function() 
       {
          if (xhttp.readyState == 4 && xhttp.status == 200) 
          {
             console.log("UPLOAD SUCCESSFUL: " + xhttp.statusText);
             console.log("GET ALL: " + xhttp.getAllResponseHeaders());
          }
          else {
              console.log("UPLOAD FAILED!")
          }
       }
    
    1 回复  |  直到 7 年前
        1
  •  0
  •   Marcelo Vismari    7 年前

    出于安全原因,不能手动设置文件。而是使用文件输入元素:

    var xhttp = new XMLHttpRequest();
    var fd = new FormData();
    // fd.append("file", "img/1.png");
    fd.append("file", document.getElementById('yourInput').files[0]);