如何在api中发送图像文件作为反应js并在节点js中表达?

时间:2017-07-18 13:33:42

标签: node.js api reactjs express

此代码发送到api

        const router = new express.Router();            
router.post('/advtregistration', (req, res) => {var form = {
            'X-API-KEY': API_KEY, 
            'advreg':req.body.userdata,
        };


       var formData = querystring.stringify(form);
    console.log(form);
       var contentLength = formData.length;

     request({
          headers: {
          'Content-Length': contentLength,
          'Content-Type': 'application/x-www-form-urlencoded'
          },
         uri: BASE_API+'Webapi_adv/advreg',
         body: formData,
         method: 'POST',

    }).pipe(res)

});

这是在表单提交上调用的函数

  processForm(event) {
// prevent default action. in this case, action is the form submission event
event.preventDefault();

// create a string for an HTTP body message

//const email = encodeURIComponent(this.state.user.email);
//const password = encodeURIComponent(this.state.user.password);

const errors = {} ;
var styling = {
   visibility: 'visible'     
};

this.setState({
      errors
});

this.state.user.company_logo=localStorage.getItem("logo");
const userdata =JSON.stringify(this.state.user);

const formData = `userdata=${userdata}`;
// create an AJAX request
const xhr = new XMLHttpRequest();
xhr.open('post', '/auth/advtregistration');
xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhr.responseType = 'json';
xhr.addEventListener('load', () => {
  if (xhr.status === 200) {
      console.log(xhr.response);          
     if(xhr.response.result.status_code=='0'){             
          browserHistory.push('/reg_success');          
     }else{
            errors.summary = xhr.response.result.status_message;
            errors.style   = styling ;
            errors.class= 'error_cont' ;
              this.setState({
                errors
              });
     }        


  } else {
    // failure

    // change the component state
    const errors = xhr.response.errors ? xhr.response.errors : {};
    errors.summary = xhr.response.message;
    errors.style   = styling ;
    errors.class= 'error_cont' ;

    this.setState({
      errors
    });
  }
});
xhr.send(formData);

}

这是我的html输入文件

    

//这是我的函数,它将调用文件部分

  encodeImageFileAsURL(element) {

  var file= document.querySelector('#file-4').files[0];
            var reader = new FileReader();
            reader.onloadend = function(e) { 
               localStorage.setItem("logo", reader.result);
                 $('.blah').attr('src', e.target.result);
            }
           reader.readAsDataURL(file);

}

此代码在api上发送base64图像时有效,但想通过api发送图像文件,请帮助,谢谢

0 个答案:

没有答案