upload image binary - using imageshack api

后端 未结 2 696
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-12 04:54

Moving a topic from google groups to here so it can help someone who is asking.

imageshack api: http://api.imageshack.us/

the final http reqeust is returning

2条回答
  •  旧巷少年郎
    2020-12-12 05:37

    What worked for me was reading about

    • the differences between URI's, files, blobs and Base64's in this article: https://yaz.in/p/blobs-files-and-data-uris/ .
    • fetching a new blob: https://masteringjs.io/tutorials/axios/form-data
    • and much more closed tabs along the way

    so in my react component onChange handler I use new FileReader to read event.target.files[0], readAsDataURL(file), and set the Base64 encoded string to state.

    I conditionally render an img src={base64stringfromState} to offer confirmation of correct image, then onSubmit, I convert this "Data URI" (the Base64 string), to a blob with one of these two codes I found somewhere (didn't end up using the first one but this is useful af and took forever to find):

    const dataURItoBlob = (dataURI) => {
        // convert base64/URLEncoded data component to raw binary data held in a string
        var byteString;
        if (dataURI.split(',')[0].indexOf('base64') >= 0)
            byteString = atob(dataURI.split(',')[1]);
        else
            byteString = unescape(dataURI.split(',')[1]);
        // separate out the mime component
        var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
        // write the bytes of the string to a typed array
        var ia = new Uint8Array(byteString.length);
        for (var i = 0; i < byteString.length; i++) {
            ia[i] = byteString.charCodeAt(i);
        }
        return new Blob([ia], {type:mimeString});
    }
    

    And

    const blob = await fetch(base64imageString).then(res => res.blob())
    

    Instead of all that shit we can just do this fetch a new version of the image or whatever and blob it right there, in the middle of constructing our photo upload/request :

    event.preventDefault()
    const blob = await fetch(base64stringfromState).then(res => res.blob())
    const formData = new FormData()
    formData.append('file@', blob)
    formData.append('api_key', 'XXXXX')
    formData.append('auth_token', 'XXXXXXXXXX')
    formData.append('album', 'youralbumname')
    const res = await axios.post('https://api.imageshack.com/v2/images', formData, {headers{'Content-Type':'multipart/form-data'}})
    

    then all we have to do to store the uploaded image is to append https:// to and record the returned direct link for storage alongside its id so you can delete it if you need to later. Per the code earlier they spit out at

    res.data.result.images[0].direct_link
    res.data.result.images[0].id
    

    This was a bitch to solve so hopefully this helps someone else with uploading photos to imageshack api cuz it's potentially a great value considering the limits of the competitors.

提交回复
热议问题