简体   繁体   中英

Correct way of sending image via AJAX in JSON to Rocket server

I am trying to build a Rust Web App using Rocket that uploads images from the client.

My problem is that I don't know how to encode the data of an uploaded image (the pixels) into a JSON on the client side. This data would be later send via AJAX.

The POST request here complains that image is not a String , but a map . That is understandable but what I really would like to do is to POST the correct data in the Javascript side (image in the xhr.send() ), because I believe that is the part that I am missing.

use rocket_contrib::json::{Json, JsonValue};

#[derive(Deserialize)]
pub struct Image {
    file_type: String,
    image: String,
    message: String,
}

#[post("/img_upload", data = "<image>")]
pub fn upload(image: Json<Image>) -> JsonValue {
    // here the back end should do some obscure matrix multiplications
    json!({
            "message": format!("Message {} received", image.0.message),
            "received_type": image.0.file_type,
            "image": image.0.image,
    })
}

The image is uploaded by the client:

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8" />
    <title></title>
  </head>
  <body>
    <input type="file" name="fileb" id="fileb" />
  </body>
<script src="./main_moc.js">
</script>

And this is main_moc.js .

var target_brows = document.getElementById("fileb");

target_brows.addEventListener('change', loadDoc);

// POST REQUEST TO SERVER: upload image
function loadDoc(event) {
  var input = target_brows;
  var file = input.files[0];
  console.log(file);
  if (validFileType(file)) {

    var xhr = new XMLHttpRequest();
    xhr.open("POST", "/img_upload");
    xhr.onload = function(e) {

      if(xhr.status === 200) {
        console.log("Received stuff");
        var data = JSON.parse(xhr.responseText);
        console.log(data);
      } else {
        console.log("Some error:");
        console.log(xhr.responseText);
      }
    }

    xhr.send(JSON.stringify({
      "file_type": file.type,
      "image": file,
      "message": "Apples"
    }));

  }

}

I also tried to write an image from the file into a canvas and the send data using context.getImageData() but that wasn't working either (error on the client side).

I think I have managed to solve the problem. I use the File API to read the input and then I submit it via POST request.

I am still unsure if this is the best way to do it but at least I can handle it on the server side.

function loadDoc(event) {
  // cancel default actions
  var file = target_brows.files[0];
  var fr = new FileReader();
  fr.onload = function () {
    var xhr = new XMLHttpRequest();
    xhr.open("POST", "/img_upload");
    xhr.onload = function(e) {
      //The response of the upload
      xhr.responseText;
      if(xhr.status === 200) {
        console.log("Received stuff");
        var data = JSON.parse(xhr.responseText);
        console.log(data);
      } else {
        console.log("Some error:");
        console.log(xhr.responseText);
      }
    }

    xhr.send(JSON.stringify({
      "file_type": file.type,
      "image": fr.result,
      "message": "Apples"
    }));
  }
  fr.readAsDataURL(file);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM