访问或显示需要授权的上传图像

时间:2018-04-12 09:29:41

标签: javascript reactjs

我可以通过在授权标头中提供access_token等来成功上传图片,然后返回一个downloadURL。对于上传,我的目的是:

let res = await fetch(URL, {
      method: 'POST',
      headers: {
        Authorization: `Bearer ${token}`
      },
      body: data
    })
      .then(response => {
        return response.json()
      })
      .then(data => {
        return data
      })
      .catch(error => {
        return error
      })

现在,我希望downloadURL在html <img />标记中显示为“

const downlaodURL = '/download/pid1/VwXLvSKQzp/Selection_006.png' 
<img src=`${downloadURL}`alt='image not found' />

但是当我尝试访问该图片时,它表示您未经过身份验证: unauthenticated image

如何在HTML标签中访问或显示它?

我有很多图像,我在循环中渲染它:

{images ? images.map((img, index) => (
                    <PinnedImage
                      key={index}
                      name={img.mediaName}
                      picture={img.downloadURL}
                      url={img.downloadURL}
                    />
                  )) : null} 

在PinnedImage组件中:

<img className="imgHeight" src={this.props.picture} alt="image not found" />

如何展示?我是否应该再次为所有图像使用下一个经过身份验证的服务器?

1 个答案:

答案 0 :(得分:1)

尝试在PinnedImage组件中执行AJAX调用,以检索如下图像 PinnedImage.jsx

export class PinnedImage extends Component
{
 constructor(props)
 {
  super(props);
  this.state={image:''}
 }
componentWillMount()
{
const downlaodURL = '/download/pid1/VwXLvSKQzp/Selection_006.png' 
await fetch(downlaodURL , {
  method: 'GET',
  headers: {
    Authorization: `Bearer ${token}`
  }
 })
  .then(response => {
    return response.json()
  })
  .then(data => {
    this.setState({image:data});
  })
  .catch(error => {
    return error
  })

}

}

现在this.state.image包含可以在任何React生命周期方法中引用的实际图像数据(可能是blob类型),如render()。

 <img className="imgHeight" src={this.state.image} alt="image not found" />