如何在ReactJS中将数据二进制转换为图像? [英] How to convert data binary into image in reactjs?
问题描述
我已经在尝试这种方法,但是它仍然对我不起作用 如何在reactjs中将二进制数据转换为图像
I'm already trying this, but it still not working for me how to convert the binary data to image in reactjs
这里是我的代码
return axios.post(`${API_MOBILE}/${path}`, formData, {
headers: {
'Content-Type': 'multipart/form-data',
},
})
.catch((error) => {
if (error.response) {
return Promise.reject({
message: error.response.data.error,
code: error.response.status
});
} else if (error.request) {
console.log(error.request);
throw error;
} else {
console.log('Error', error.message);
throw error;
}
});
},
此处是控制器
try {
let { detail } = yield select(state => state.user);
const result = yield call(API.generateMotif, payload, detail.api_token);
yield put({
type: types.GENERATE_MOTIF_SUCCESS,
payload: result,
});
} catch (err) {
yield put(handleError(err));
yield put({
type: types.GENERATE_MOTIF_FAILURE,
payload: err,
});
}
这是我的前端
<div className="box-body">
{ props.uploading
? (
<div>
<img src={props.image} alt="upload placeholder"/>
<Spinner />
</div>
)
: props.generated !== ''
? <img src={"data:;base64,"+props.generated} alt="generated motif"/>
: <AddPhotoAlternate className="icon-large"/>
}
</div>
GenerateM.propTypes = {
image: PropTypes.string.isRequired,
generated: PropTypes.string,
list: PropTypes.array,
uploading: PropTypes.bool.isRequired,
imageChange: PropTypes.func.isRequired,
};
在我的控制台中,generated
具有二进制数据,因此我在发布的那个链接中找到了解决方案,但仍然对我不起作用.我想要的响应,在我的前端显示图像中,但是在这里,我得到的响应
它只是我从Postman复制的一小段响应,当我从控制台复制时,它只是没有复制任何内容.
����JFIF��C $.' ",#(7),01444'9=82<.342��C 2!!22222222222222222222222222222222222222222222222222��"�� ���}!1AQa"q2���#B��R��$3br� %&'()*456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz��������������������������������������������������������������������������� ���w!1AQaq"2�B���� #3R�br�
就像这张照片
In my console, generated
has data binary, so I found solutions in that link that I post, but it still not working for me. Response that I want, in my frontend show image, but here the response that I got
it just snippet of response that I copying from Postman, when I copying from my console it just has copying nothing.
����JFIF��C $.' ",#(7),01444'9=82<.342��C 2!!22222222222222222222222222222222222222222222222222��"�� ���}!1AQa"q2���#B��R��$3br� %&'()*456789:CDEFGHIJSTUVWXYZcdefghijstuvwxyz��������������������������������������������������������������������������� ���w!1AQaq"2�B���� #3R�br�
like in this picture
您有什么可以帮助我的解决方案吗?拜托,任何建议对我都会很有帮助.
did you have any solutions that can help me? please, any suggestion will be very helpful for me.
推荐答案
您可以执行以下操作:
<img src={`data:image/*;base64,${props.generated}`} alt="generated motif" />
但是您必须确保来自API的响应是可以解码的.
But you must ensure response from your API is something that can be decoded.
请参见PHP的 base64_encode()
和此Stackoverflow答案.
这篇关于如何在ReactJS中将数据二进制转换为图像?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!