Tuesday, 9 May 2017

Angular 2 - image is broken after I posted to upload api

Anyone has experience using form data to post to the server especially upload image


I'm using this package = https://github.com/request/request#multipartform-data-multipart-form-uploads
server file
import * as Promise from "bluebird";
import * as cheerio from "cheerio";
import * as request from "request-promise";

const endpoint = "http://example.com/api/fileupload";
return request.post(endpoint, {
  form: {
    DeveloperKey: DEV_KEY,
    Action: "Insert",
    Test: "True",
    email: "abc@abc.com",
    filename: "1492768174.png",
    filemimetype: "png",
    file: bytes   //doesn't work 
  }
}).then(res => {
console.log(res);
const $ = cheerio.load(res, { xmlMode: true });
const errors = $("Errors").toArray().map(element => ({ message: $(element).text() }));
const externalId = $("ResponseExternalID").text();
const status = $("Status").text();
(status === "Success");
console.log(errors, externalId, status);
return { errors, externalId, status };
});

component file

onChange(event) {
    this.file = event.srcElement.files[0];
    let myReader: FileReader = new FileReader();
    myReader.readAsBinaryString(this.file);
    myReader.addEventListener("load", () => {

      const imageContent = btoa(myReader.result);
      this.imageBinaryString = imageContent;
      // console.log("binaryString", binaryString);
    }, false);
  }

html file

  <div>
    <input type="file" id="photo" (change)="onChange($event)" />
  </div>



via weikian

No comments:

Post a Comment