难走的路都是上坡路!共勉!
产品:上传照片的时候,保证图片大小一致,都是800*600。
程序员: 好的。
思考过程: 上传文件的行为,前端获取到的是File对象,需要通过FileReader构造函数读取文件流生成一个可以加载图片的src,并在加载之后赋值给img,通过img.naturalWidth和img.naturalHeight拿到原始图片的大小,不要忘记要在img.onload方法中获取,否则拿到的就是0了。
import React from 'react';
import { Upload, Button, message } from 'antd';
export default () => {
const props = {
name: 'file',
action: 'https://www.mocky.io/v2/5cc8019d300000980a055e76',
headers: {
authorization: 'authorization-text',
},
beforeUpload: async (file) => {
return new Promise((resolve, reject) => {
if (file.type.startsWith('image/')) {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => {
const img = new Image();
img.src = reader.result;
img.onload = () => {
console.log(img.naturalWidth, img.naturalHeight);
if (img.naturalWidth !== 800 || img.naturalHeight !== 600) {
message.info('图片尺寸必须是800*600');
reject();
} else {
resolve();
}
};
};
}
});
},
onChange(info) {
if (info.file.status !== 'uploading') {
console.log(info.file, info.fileList);
}
if (info.file.status === 'done') {
message.success(`${info.file.name} file uploaded successfully`);
} else if (info.file.status === 'error') {
message.error(`${info.file.name} file upload failed.`);
}
},
};
return (
<div>
<h3>
限制图片最大尺寸 width: {800}, height: {600}
</h3>
<Upload {...props}>
<Button>上传</Button>
</Upload>
</div>
);
};
前端程序员干了六年了,也没有写过文章,没有写过总结,实在惭愧,也不知道自己这些年忙忙碌碌在干些什么,玩也没有玩好,技术上也就只是个搬砖工,没有自己的沉淀,也没有好好研究过源码,就这么浑浑噩噩的六年过去了,希望现在觉醒不会太晚吧!
当前大环境不好,互联网就业形势也不乐观,有的人几个月都找不到工作,有的找到了工作刚入职两个月又被裁,本人也在十月底喜提大礼包,切实感受到了互联网行业的寒冬,大家能在原公司呆着就先呆着吧,外面的日子更不好过。
第一次发布,文章如有不当之处,感谢留言指正!