简体   繁体   English

python 请求 POST 图像到二进制数据

[英]python requests POST image to binary data

def change_img(self, good_uid, image):
    data = {
        "file": image,
        "old_image_hosting_url": "",
        "goods_uid": good_uid,
        "image_type": "main",
    }
    headers = {
        "Accept": "text/html, */*; q=0.01",
        "Referer": self.BASE_URL
        + f"/mall/admin/admin_goods_image_upload.php?image_type=main&goods_uid={good_uid}&image_id=main_0",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/104.0.0.0 Safari/537.36",
        "X-Requested-With": "XMLHttpRequest",
    }
    response = self.session.post(
        url=self.BASE_URL + "/mall/admin/admin_goods_image_upload_ok.php",
        headers=headers,
        data=data,
    )
    if response.status_code == 200:
        print(response.elapsed.total_seconds())
        return True


resp = requests.get(url=url, stream=True)
if resp.status_code == 200:
    img = np.asarray(bytearray(resp.raw.read()), dtype="uint8")

    decoded_img = cv2.imdecode(img, flags=1)
    bg_removed_img = remove(decoded_img)
    retval, buffer = cv2.imencode(".png", bg_removed_img)

    change_img(..., buffer)

The upper code I wrote is a code that POST image data to the following url.我写的上面的代码是一个POST图像数据到下面url的代码。 However, I don't think the image is correctly POSTED.但是,我认为该图像未正确发布。

  • I think I am not POSTING image binary file *我想我不是在发布图像二进制文件 *

How can I fix this code?如何修复此代码?

  • i've uploaded the js code from the website.我已经从网站上传了js代码。
var goods_uid = "145690";
var image_id = "main_0";
var image_type = "main";
var image_hosting_url = "https://tmgdisk01.cafe24.com/";
var pmode = "";

var old_image_hosting_url = "";
if (image_id) {
  old_image_hosting_url = $("#" + image_id, opener.document).attr("hosting");
  old_image_hosting_url = old_image_hosting_url.replace(
    "{HOST}",
    image_hosting_url,
  );
}

$(document).ready(function () {
  var fileTarget = $(".filebox .upload-hidden");

  fileTarget.on("change", function () {
    if (window.FileReader) {
      // 파일명 추출
      var filename = $(this)[0].files[0].name;
    } else {
      // Old IE 파일명 추출
      var filename = $(this).val().split("/").pop().split("\\").pop();
    }

    $(this).siblings(".upload-name").val(filename);

    var fd = new FormData();
    var files = $("#input_file")[0].files[0];
    fd.append("file", files);
    fd.append("old_image_hosting_url", old_image_hosting_url);
    fd.append("goods_uid", goods_uid);
    fd.append("image_type", image_type);

    $.ajax({
      url: "admin_goods_image_upload_ok.php",
      type: "post",
      data: fd,
      contentType: false,
      processData: false,
      success: function (response) {
        //console.log("==> aaaa : "+response);
        //console.log("==> pmode : "+pmode);
        //console.log("==> goods_uid : "+goods_uid);

        if (response && response != "null") {
          try {
            var result = jQuery.parseJSON(response);
            var status = result["status"];
            var image_url = result["url"];
            var msg = result["msg"];

            var image_url2 = "";

            if ("undefined" != typeof image_url)
              image_url2 = image_url.replace("{HOST}/", image_hosting_url);

            if (status == "success" && image_url) {
              if (goods_uid && image_id) {
                var parent_input = image_id + "_input";

                $("#" + image_id, opener.document).attr("src", image_url2);
                $("#" + image_id, opener.document).attr("hosting", image_url);

                $("#" + parent_input, opener.document).val(image_url2);

                opener.parent.image_save(
                  image_type,
                  goods_uid,
                  image_id,
                  "",
                  "",
                );

                window.close();
              } else if (pmode == "desc" && goods_uid) {
                opener.parent.image_load(goods_uid, image_url2);
                window.close();
              } else {
                $("#result").html(msg + "<br>→ 이미지경로 : " + image_url2);
              }
            } else {
              //$("#result").html(result.msg+"<br>→ 파일 업로드가 실패되었습니다. FTP 접속정보를 확인해주세요. : "+image_url2);
              $("#result").html(msg);
            }
          } catch (e) {
            $("#result").html("@@" + response);
          }
        } else {
          alert("파일 업로드가 실패되었습니다.");
        }
      },
    });
  });

  //preview image
});

The docs say you need to put a stream or a 3-tuple into data to post a multipart/form-data file (which is probably what a.php endpoint expects). 文档说您需要将 stream 或三元组放入data中以发布多部分/表单数据文件(这可能是 a.php 端点所期望的)。

Since your image is a bytes buffer, and it's a PNG, try由于您的image是字节缓冲区,并且是 PNG,请尝试

import io

def change_img(self, good_uid, image):
    data = {
        'old_image_hosting_url': '',
        'goods_uid': good_uid,
        'image_type': 'main',
        'file': ('image.png', io.BytesIO(image), 'image/png'),
    }
    # ...

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

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