【问题标题】:access or show uploaded images that need authorization访问或显示需要授权的上传图片
【发布时间】:2018-04-12 09:29:40
【问题描述】:

我可以通过在授权标头中提供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' />

但是当我尝试访问该图像时,它表示您未通过以下身份验证:

如何访问或在 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" />

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

【问题讨论】:

    标签: javascript reactjs


    【解决方案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 保存实际的图像数据(可能是 blob 类型),可以在任何 React 生命周期方法(如 render() )中引用。

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

    【讨论】:

    • 我将在此处使用 HTTP GET 请求来访问文件和 POST,因为您的答案中有 POST 请求。对吗?
    猜你喜欢
    • 2013-10-31
    • 1970-01-01
    • 1970-01-01
    • 2014-12-28
    • 2015-07-20
    • 2017-11-16
    • 2016-01-30
    • 2021-12-31
    • 1970-01-01
    相关资源
    最近更新 更多