NodeJs API дает путь к изображению продукта - PullRequest
0 голосов
/ 02 июня 2018

Я загружаю продукт с изображением, используя API большой коммерции.Продукт успешно создан API, а изображение - нет.Как я могу указать путь назначения?

Я указал путь назначения, как показано ниже

https://store -9gk124wgzn.mybigcommerce.com / dev / product_images

Но это не работает.

const storage = multer.diskStorage({
   destination: 'https://store-9gk124wgzn.mybigcommerce.com/dev/product_images',
   filename: function(req, file, cb) {
       cb(null, file.fieldname + '-' + Date.now() + path.extname(file.originalname));
   }
});

enter image description here

Вот полный код, который я пытаюсь дать пути к изображению, которому он присвоил имя папки с изображениями buddha.jpg, но этоне передает изображение.const productCreated = function (createnewproduct) {console.log (createnewproduct);const deferred = q.defer ();const postDataOptions = {url: ${BC_STORE_URL}/api/v2/products, метод: 'POST', заголовки: {'Accept': 'application / json', 'Content-Type': 'application / json', 'Authorization': 'Basic' + newБуфер (BC_USER + ':' + BC_TOKEN) .toString ('base64')}, json: true, body: createnewproduct};request (postDataOptions, (error, res, body) => {console.log (body); if (! error && res.statusCode == 201) {console.log (createnewproduct); deferred.resolve (createnewproduct);}});вернуть deferred.promise;}

app.post('/product-created', (req, res) => {

  const createnewproduct = {
    "name": req.body.name,
    "price": req.body.price,
    "categories": [req.body.categories],
    "type": req.body.type,
    "availability": req.body.availability,
    "description": "This timeless fashion staple will never go out of style!",
    "weight": req.body.weight,
    "is_visible": true,
    "id": 549

  };


  productCreated(createnewproduct).then(result => {
    const postImgDataOptions = {
      url: `${BC_STORE_URL}/api/v2/products/${result.id}/images`,
      method: 'POST',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json',
        'Authorization': 'Basic ' + new Buffer(BC_USER + ':' + BC_TOKEN).toString('base64')
      },
      json: true,
      body: {
        //http://psdsandbox.com/022/pillow.jpg
        "image_file": "images/buddha.jpg", // this image is put in public folder
        "is_thumbnail": true,
        "sort_order": 0,
        "description": "Hi this is shutter img"
      }
    };
    request(postImgDataOptions, (error, response, body) => {
      console.log(response.statusCode);
      if (!error && response.statusCode == 201) {
        res.send('Done');
      } else {
        res.send('Bad Request');
      }
    });



  });

});

1 Ответ

0 голосов
/ 02 июня 2018

вы пытались использовать только product_images/?

и вместо использования destination: https://... использовать функцию обратного вызова примерно так:

destination: function (req, file, cb) {
    cb(null, 'product_images/')
}

ОБНОВЛЕНИЕ: , чтобы загрузить изображение, вы должны использовать formdata


var uploadData = {
    image_file: {
      value: fs.createReadStream("images/buddha.jpg),
      options: {
        filename: "buddha.jpg",
        contentType: "image/jpg"
      }
    }
  };
  var uploadOptions = {
    method: "POST",
    uri: `${BC_STORE_URL}/api/v2/products/${result.id}/images`,
    formData: uploadData
  };
  return request(uploadOptions).then(res => {
    res.send('Done');
 }).catch(function(err){
    res.send('Bad Request');
 })
...