使用Fetch API和Promise来调用Restful接口进行POST

by Clem TheDasher

HTML

<!-- Note: Demo只是为了表示一下流程,由于没有后端,无法进行上传后的处理。-->
<input id='avatarUploader' type='file'/>
<img id="avatar" src="" alt=""/>

JavaScript

const avatarUploader = document.getElementById('avatarUploader')

avatarUploader.addEventListener('change', uploadImage)

function uploadImage(e) {
	if ((e.target.files != null) && (e.target.files[0] != null)) {
  	const avatar = e.target.files[0],
    	fd = new FormData(),
     	endPoint = 'https://testtesttest.com/api/v1/' + 'images'
      
    let headers = {
      	'Accept': 'application/json'
      	}
    
    headers.Authorization = 'Bearer ' + localStorage.getItem('token')
    
    fd.append('avatar', avatar)
    
    fetch(endPoint, {
    	method: 'POST',
      headers: headers,
      body: fd
    }).then(response => response.json())
    	.then(result => {
      	if (result.image) {
        	const avatar = document.getElementById('avatar'),
          	imageUrl = result.image.url
            
          avatar.src = imageUrl
        }
        else {
        	throw result.error
        }
      })
      .catch(error => console.log(error))
  }
}