300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > antd 使用upload 组件 使用自定义上传行为 覆盖默认action 访问请求

antd 使用upload 组件 使用自定义上传行为 覆盖默认action 访问请求

时间:2024-03-30 12:28:34

相关推荐

antd 使用upload 组件 使用自定义上传行为 覆盖默认action 访问请求

今天遇到测试提起的一个项目bug。

使用antd里面的 upload 组件上传图片,本地测试使用没有问题。

当项目上传到服务器,测试 接口报405,打开控制台中的network,访问了一个没有调用的接口,nginx 报405。

网上查询资料,是upload组件上传图片默认调用了action 路径,如果未设置的话,就以当前网页的url为路径进行访问。方法为post请求进行访问静态资源。

使用customRequest属性来阻止默认上传行为

<Uploadname="avatar"listType="picture-card"className="avatar-uploader"showUploadList={false}beforeUpload={this.beforeUpload.bind(this)}onChange={this.handleChange.bind(this)}customRequest={this.uploadHeadImg.bind(this)}>{headImgUrl ? <img src={headImgUrl} alt="avatar" style={{width: '100%' }} /> : uploadButton}</Upload>

beforeUpload(file) {const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';if (!isJpgOrPng) {message.error('你只能上传 JPG/PNG 文件!');}const isLt2M = file.size / 1024 / 1024 < 2;if (!isLt2M) {message.error('图片大小必须小于 2MB!');}return isJpgOrPng && isLt2M;}handleChange (info) {if (info.file.status === 'uploading') {this.setState({ loading: true });return;}if (info.file.status === 'error') {this.setState({ loading: false });message.error('上传失败');}};uploadHeadImg(info){//这里是我自己项目封装的上传图片方法(想深入此方法的,可查看我之前的文章),此处读者可自行更改为自己的上传方法。requestFile({multipartFile: info.file},uploadFile,(res)=>{message.success('上传成功!');if(res){const headImgUrl=baseUrl+res;this.setState({headImgUrl,loading: false,})}})}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。