上传单张图片

时间:2019-06-03 22:45:26

标签: javascript jquery ajax

我有一个应用程序,您可以在其中制作卡片并上传图片。问题是我总是遇到问题,有时图片可以上传并正常工作,有时却没有。我看过很多教程和示例,但找不到错误所在。

具有文件上传功能的表单部分

<span class="event-image picture2">
    <img style="height:300px" id="promo-img-upload uploaded-picture" class="promo-img-upload" src="${eventPicture}">
    <input id="new-event-picture filename" class="img-upload filename" type="file" name="filename" accept="image/*">
</span>

AJAX通话

var formData = new FormData($($(this).closest('form'))[0]);

console.log('heeeyyy form', $($(this).closest('form'))[0]) //THIS ONE PRINTS ALL THE FORM 
console.log('formData', formData) //THIS RETURNS EMPTY

      let offerEdited = function(res) {
        let promoId = res['promotion'][0]['id']
        $('.hidden-promo-id:last').text(promoId)
        $(`#${this_form.attr('id')} .confirmation`).text('Promo Saved')
        $('.confirmation').fadeOut(3000)


            // image upload
        $.ajax({
          type: 'POST',
          url: `/api/Upload-promo?promoId=${promoId}`,
          crossDomain: true,
          data: formData,
          cache: false,
          processData: false,
          contentType: false,
          enctype: 'multipart/form-data',
          mimeType: 'multipart/form-data',
          beforeSubmit : function() {
        },
          success : function(responseText, statusText, xhr, $form) {
    $(`#promo${promoNumber}`).find('.promo-img-upload').attr('src', `https://res.cloudinary.com/hn90uqs5e/image/upload/promos/${responseText}`);

                },
          error: function(response){
            console.log('there was an error', response)
        }
     });
   }

邮政查询

router.post('/Upload-promo', function(req, res) {
  let promoId = req.query.promoId

  let upload = multer({ storage: cloudinaryPromoStorage }).single('filename')
  upload(req, res, function (err) {
    let file = req.file
    if(file != undefined) {
      let fullFileName = file["public_id"]
      regex = /(promos\/)(.+)/
      let fileName = fullFileName.match(regex)[2]
      if (err) {
        return res.send("Error: file not uploaded")
      }

      db.any("UPDATE promotions set event_picture = $1 WHERE id = $2", [fileName, promoId])
      .catch(function(err){
        console.log(err)
      })
      return res.send(fileName)
    }
  })

})

0 个答案:

没有答案