【问题标题】:Simplest possible upload javascript example without forms没有表单的最简单的上传 javascript 示例
【发布时间】:2019-09-19 19:51:17
【问题描述】:

我发布这个是因为很难在一个地方找到我的用例的信息。最初的任务听起来很简单:“如何将通过网页上的文件类型输入标签选择的文件上传到能够解析 POST 请求的简单 http 服务器?”。不幸的是,我花了几天时间寻找可以在不强迫我使用表格的情况下提供帮助的材料。

【问题讨论】:

  • 有什么问题?解决方案应该是答案,而不是问题。
  • 我已重新格式化以使问题特别清晰,并将我的解决方案移至第一个答案区域。你会重新评估否决@Barmar 吗?
  • 抱歉,我无法撤消其他人的反对票。
  • 还有其他关于使用纯 JavaScript 上传文件的问题。您可以将答案添加到其中之一,而不是创建新问题。

标签: javascript csv server upload fetch


【解决方案1】:

我想提供我最终发现的东西来做到这一点,希望它可以帮助其他人。

有用的信息取自 File Upload without Formhttps://blog.anvileight.com/posts/simple-python-http-server/https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

干杯


index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title></title>
  <script src="test.js"></script>
</head>
<body>
    <input type="file" name="fileload">
    <button id="bttn">submit</button>
</body>
</html>

test.js

let run = ()=> {let inpt = document.querySelector("input")
  let f
  inpt.onchange =()=> {
    f = inpt.files[0]
  }
  let btn = document.querySelector("#bttn")
  btn.addEventListener("click",()=> {
    console.log("clc")
    let xmlHttpRequest = new XMLHttpRequest();

    let fileName = f.name
    let target = "http://localhost:8080"
    let mimeType = "text/csv"

    //xmlHttpRequest.open('POST', target, true);
    //xmlHttpRequest.setRequestHeader('Content-Type', mimeType);
    //xmlHttpRequest.setRequestHeader('Content-Disposition', 'attachment; filename="' + fileName + '"');
    //xmlHttpRequest.send(f);
    fetch("http://localhost:8080",{
      method:"POST",
      mode:"cors",
      headers:{
        "Content-type":"text/csv",
        "Content-disposition":`attachment;filename=${fileName}`
      },
      body:f
    }).then(
      res=> {
        console.log(res)  
        res.text()
      }
    ).then(text=> console.log(text))
  })
}
window.onload = ()=> {
  run()
}

pyserv.py

from http.server import HTTPServer, SimpleHTTPRequestHandler

from io import BytesIO


class TestingRequestHandler(SimpleHTTPRequestHandler):
    def do_GET(self):
        super().do_GET()
    def do_POST(self):
        print("--- headers \n{} ---".format(self.headers))
        print("whole self --\n{}--".format(self))
        content_length = int(self.headers['Content-Length'])
        print(self.rfile,"is rfile")
        body = self.rfile.read(content_length)
        print("body is ",body)
        self.send_response(200)
        self.end_headers()
        response = BytesIO()
        response.write(b'This is POST request. ')
        response.write(b'Received: ')
        response.write(body)
        self.wfile.write(response.getvalue())


httpd = HTTPServer(('localhost', 8080), TestingRequestHandler)
httpd.serve_forever()

【讨论】:

    猜你喜欢
    • 2017-09-27
    • 2013-05-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-30
    相关资源
    最近更新 更多