简体   繁体   English

从js前端上传json文件到zhttp后端

[英]Upload json file from js frontend to zhttp backend

I have js code for upload json file with content我有用于上传 json 文件内容的 js 代码

{"name": "John", "age": 35}

from frontend js with using POST to scala zhttp backend.从使用 POST 的前端 js 到 scala zhttp 后端。 JS code: JS代码:

    <script>
        async function loadJsonTests() {
             console.log('Begin loading new JSON file with tests into server.');
             let formData = new FormData();
             let url = `load_test`;
             formData.append("file", fileupload.files[0]);
                 let response = await fetch(url, {
                   method: "POST",
                   headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json'
                   },
                   body: formData
                   //body: JSON.stringify({name: 'John', age: 35})
                 });
             return response.json();
        }

        async function btnUploadTestFile() {
             const result = await loadJsonTests();
             console.log(result);
        }
    </script>

html for upload file and call js function html 用于上传文件和调用js function

            <td width="70%" height="200px">
                <input id="fileupload" type="file" name="fileupload" />
                <br>
                <div id="btn_upload_test_file" onclick="btnUploadTestFile()">send json file</div>
            </td>

Scala build.sbt part Scala build.sbt 部分

ThisBuild / scalaVersion := "2.12.15"

  val Versions = new {
    val zio        = "2.0.5"
    val zio_config = "3.0.7"
    val z_http     = "2.0.0-RC11"
    val zio_json   = "0.3.0-RC11"
  }
  lazy val dependencies =
    new {
      val zio = "dev.zio" %% "zio" % Versions.zio

      val zio_conf          = "dev.zio" %% "zio-config"          % Versions.zio_config
      val zio_conf_typesafe = "dev.zio" %% "zio-config-typesafe" % Versions.zio_config
      val zio_conf_magnolia = "dev.zio" %% "zio-config-magnolia" % Versions.zio_config

      val z_http = "io.d11" %% "zhttp" % Versions.z_http

      val zio_json = "dev.zio"       %% "zio-json"       % Versions.zio_json

      val zioDep = List(zio, zio_conf,zio_conf_typesafe,zio_conf_magnolia, z_http, zio_json )
    }

Scala backend code Scala 后台代码

  def apply(): Http[Any, Throwable, Request, Response] =
    Http.collectZIO[Request] {
      case req@(Method.POST -> !! / "load_test") => loadTest(req)
    }

  def loadTest(req: Request): ZIO[Any, Throwable, Response] =
    for {
      bodyStr <- req.body.asString
      _ <- ZIO.logInfo(s"req JSON str = $bodyStr")
      u <- req.body.asString.map(_.fromJson[User])
      resp <- u match {
        case Left(e) =>
          ZIO.debug(s"Failed to parse the input: $e").as(
            Response.text(e).setStatus(Status.BadRequest)
          )
        case Right(u) =>
          ZIO.succeed(Response.json(u.toJson))
      }
    } yield resp

Whan I do post request from js I have next error:当我从 js 发布请求时,出现下一个错误:

message="req JSON str = ------WebKitFormBoundary11BJkIQrpt39tJXd
Content-Disposition: form-data; name="file"; filename="tests_set_1.json"
Content-Type: application/json

{"name": "John", "age": 35}
------WebKitFormBoundary11BJkIQrpt39tJXd--
" location=webui.WebUiApp.loadTest file=WebUiApp.scala line=51
Failed to parse the input: (expected '{' got '-')

How I can extract only json content from body, without additional information ------WebKitFormBoundary..... ?我如何才能从正文中仅提取 json 内容,而无需其他信息 ------WebKitFormBoundary.....?

If I send json from js如果我从 js 发送 json

body: JSON.stringify({name: 'John', age: 35})

, not a file, then everything ok. ,不是一个文件,然后一切正常。

Your backend expects a plain body as a string that you then parse as a JSON.您的后端需要一个纯正文作为字符串,然后您将其解析为 JSON。

But your frontend is sending form data with a file, that's a different type of content in the HTTP request.但是您的前端正在发送带有文件的表单数据,这是 HTTP 请求中不同类型的内容。

Either your backend must be modified to read formdata (instead of a plain string), or in your frontend read the file content and send only the file content.必须修改您的后端以读取表单数据(而不是纯字符串),或者在您的前端读取文件内容并仅发送文件内容。

You can use the FileReader to get the contents of the file and then send the content only您可以使用FileReader获取文件的内容,然后仅发送内容

https://developer.mozilla.org/en-US/docs/Web/API/FileReader?retiredLocale=en https://developer.mozilla.org/en-US/docs/Web/API/FileReader?retiredLocale=en

fileInputElement.change(function(e) {
  var reader = new FileReader();
  reader.onload = function(e) {
    console.log(reader.result);
  }
  reader.readAsText(fileInput[0].files[0]);   
});

Fixed with next.js code:修复了 next.js 代码:

    <script>
        function loadFile(file){
            return new Promise(resolve=>{
                let reader = new FileReader()
                reader.onload = function(event) {
                    let data = event.target.result
                    resolve(data)
                }
                reader.readAsText(file)
            })
        }

        async function loadJsonTests() {
             console.log('Begin loading new JSON file with tests into server.');
             var file = fileupload.files[0];
             var fileContent = await loadFile(file);
             console.log('-- request ----------------------------------------------');
             console.log(fileContent);
             console.log('---------------------------------------------------------');
              const response = await fetch(`load_test`, {
                   method: "POST",
                   headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json'
                   },
                   body: fileContent
                 });
             return response.json();
        }

        async function btnUploadTestFile() {
             const resultJson = await loadJsonTests();
             console.log('-- response ---------------------------------------------');
             console.log(resultJson);
             console.log('---------------------------------------------------------');
        }
    </script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何从后端节点 js 获取 Json 数据到前端 html - How to get Json data from backend node js to frontend html 将 JSON 从后端发送到前端 - Sending JSON from backend to frontend 将文件从 React.JS 前端移动到 C++ 后端 - Moving a file from a React.JS frontend to a C++ backend 如何将 mp3 文件从 Java 后端发送到前端并在 Vue.js 前端播放文件 - How to send mp3 file from Java Backend to frontend and play the file in the Vue.js frontend 如何将图片从前端上传到后端 - how to upload image from frontend to backend 无法通过我的前端从我的节点 js 服务器下载图像文件(我的后端和前端是解耦的) - Failed to download an image file from my node js server through my frontend (my backend and frontend are decoupled) 如何在从 .net 后端到 js 前端的 2 个大嵌套 json 之间执行 JSON 差异/补丁? - how to do a JSON diff/patch between 2 big nested json from .net backend to js frontend? 如何从前端的后端下载excel文件? - How to dowload an excel file from backend in frontend? 从前端发送.wav 文件到 Flask 后端 - Sending .wav file from frontend to Flask backend 无法在前端使用 Fetch API 将文件上传到 FastAPI 后端 - Cannot Upload File to FastAPI backend using Fetch API in the frontend
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM