[React+Nest.js]仿Antd實現一個圖片上傳的組件

實現效果圖

功能預覽

  1. 【less】上傳文件的input框樣式的改造
  2. 獲取圖片列表
  3. 點擊上傳圖片 + 轉換成base64
  4. 上傳中loading
  5. 上傳失敗
  6. 刪除圖片
  7. 查看大圖
  8. 下載圖片 + Blob URL
  9. useState 與 useEffect的使用
  10. 跨域
  11. 靜態文件的查看
  12. 查詢/刪除/添加文件
  13. uuid
  14. 用同步的方式書寫異步的操做(封裝 async await promise集合體)
  15. axios

【前端】React

1.【less】上傳文件的input框樣式的改造

<div className="upload-container item">
    <Icon type="plus" className="icon"/>
    <div className="name">Upload</div>
    <input id="upload-image" 
           type="file" 
           name="image" 
           accept="image/*"
           onChange={()=>handleUploadImage(props)}/>                    
</div>
複製代碼

主要用到的是原生的input框:
type="file"彈出選擇上傳文件的框;
accept="image/*"來限制你選擇上傳的文件只能是圖片類型的;
當你彈出選擇文件的框以後,不管是選擇仍是取消都會觸發onChange事件。前端

原生input上傳文件的樣式很醜,因而換樣式成了重中之重!react

思路:
1.把input框給隱藏掉
2.而且要設置一個與最終樣式一樣大小的寬高,經過子絕父相讓input框覆蓋在最上層,這樣纔可以命中點擊事件ios

.upload-container{
    margin: 5px;
    padding: 3px;
    float: left;
    border-style: dashed;
    background-color: #f5f5f5;
    position: relative; //父相
    flex-direction: column;

    .icon{
      color: #e1e1e1;
      margin-top: 10px;
      font-size: 40px;
      font-weight: bolder;
    }
    .name{
      color: #a3a3a3;
    }
    input{
      width: 100%;
      height: 100%; // 與父樣式等寬高
      cursor: pointer;
      position: absolute; // 子絕
      top: 0;
      opacity: 0; // 全透明
    }
  }
複製代碼

2. 用同步的方式書寫異步的操做(封裝 async await promise集合體)+ 獲取圖片列表 + useState

const baseUrl = 'http://localhost:8080/image';

const getImageListUrl = `${baseUrl}/list`;

const [list, setList] = useState([]);

const ajax = (url, data={}, type='GET') =>{
    return new Promise((resolve)=>{
        const promise = type === 'GET' ? axios.get(url, {params: data}) : axios.post(url, data)
        promise.then(res=>{
            const data = res.data;
            data.status !== 0 ? message.error(data.msg) : resolve(data);
        }).catch(err => {
            message.error('Network request Error: '+err);
        })
    })
};

const getAndUpdateImageList = async(setList) => {
    const data = await ajax(getImageListUrl);
    setList(data.data);
};
複製代碼

3. 點擊上傳圖片 + 轉換成base

出現上傳文件的框,不管是選擇仍是取消,都會觸發onChange事件,因此要判斷你選擇的targetFile是否存在。git

經過FileReder將圖片轉成base64,用同步的方式將最終結果拋出去:github

const getBase64 = (file) => {
    const fileReader = new FileReader();
    fileReader.readAsDataURL(file);
    return new Promise((resolve)=>{
        fileReader.onload = (data) => {
            resolve(data.target.result)
        }
    })
};
複製代碼

獲取到了base64以後再發送axios請求到後端:ajax

const handleUploadImage= async ({list,action,uploadImage,setUploadLoading, setUploadErrorFileName})=>{
    const input = document.getElementById('upload-image');
    const targetFile = input.files[0];
    if (targetFile){
        setUploadLoading(true);
        const { name } = targetFile;
        const imageBase64 = await getBase64(targetFile);
        await axios.post(action, {imageBase64, name})
            .then(()=>{
                uploadImage(action + "/" + name);
            }).catch(() => {
                setUploadErrorFileName(name);
            });
        setUploadLoading(false);
    }
};
複製代碼

4. 上傳中loading

當咱們開始上傳圖片的時候,會將uploadLoading設置成true,上傳成功以後會將uploadLoading再設置成false!axios

const handleUploadImage= async ({list,action,uploadImage,setUploadLoading, setUploadErrorFileName})=>{
    const input = document.getElementById('upload-image');
    const targetFile = input.files[0];
    if (targetFile){
        setUploadLoading(true);
        ...
        setUploadLoading(false);
    }
};
複製代碼
const [uploadLoading, setUploadLoading] = useState(false);

{uploadLoading && renderUploading()}

const renderUploading =()=> (
    <div className="uploading item">
        <Icon className="icon" type='loading' />
        <span>Uploading...</span>
    </div>
);
複製代碼

5. 上傳失敗

與loading其實同理, 其次,上傳失敗以後設置uploadErrorFileName來渲染失敗的樣式。後端

await axios.post(action, {imageBase64, name})
            .then(()=>{
                ...
            }).catch(() => {
                setUploadErrorFileName(name);
            });
複製代碼
const [uploadErrorFileName, setUploadErrorFileName] = useState(null);

{uploadErrorFileName && renderUploadError(uploadErrorFileName,setUploadErrorFileName)}

const renderUploadError =(uploadErrorFileName, setUploadErrorFileName)=> (
    <div className="uploading item error">
        <Icon className="icon" type='close-circle' />
        <div className="error-message">Error!</div>
        <div className="name">{uploadErrorFileName}</div>
        <div className="config item">
            <Icon className="delete-icon" type="delete" onClick={()=> setUploadErrorFileName(null)}/>
        </div>
    </div>
);
複製代碼

6. 刪除圖片

const deleteImage = async ({name}, setList)=>{
    await ajax(deleteImageUrl,{name});
    getAndUpdateImageList(setList);
};
複製代碼

7. 查看大圖

用到了Antd的上傳圖片同樣,用到的Modal框去顯示大圖, 用previewSrc保存選擇的結果跨域

const [previewSrc, setPreviewSrc] = useState(null);

 <Modal
    width={800} 
    className="preview-modal"
    visible={previewSrc !== null}
    title={null}
    footer={null}
    onCancel={()=>setPreviewSrc(null)} >
         <img src={previewSrc} alt=""/>
</Modal>
複製代碼

8. 下載圖片 + blob

思路:
1.用a標籤的download屬性來實現下載效果,由於下載按鈕是Icon,因此點擊download Icon以後觸發a標籤的downloadpromise

2.使用Blob: 使用URL.createObjectURL()函數能夠建立一個Blob URL

<Icon type="download" className="icon" onClick={()=>downloadImage(item, onDownload)}/>
<a id="download-image"  download={item.name}/>
複製代碼
const downloadImage=(item, onDownload)=>{
    const target = document.getElementById('download-image');
    const blob = new Blob([item.src]);
    target.href = URL.createObjectURL(blob);
    target.click();
    onDownload(item);
};
複製代碼

【後端】Nest

1.跨域

app.enableCors();
複製代碼

2.靜態文件暴露

const app = await NestFactory.create<NestExpressApplication>(AppModule);
  app.useStaticAssets(join(__dirname, '..', 'data/images'), {
    prefix: '/images/',
  });
複製代碼

3.寫文件

  1. 解析base64,生成buffer
  2. fs.writeFile(buffer)
@Post('/image/add')
  getImage(@Req() req, @Res() res): void {
    const {imageBase64, name} = req.body;
    const base64Data = imageBase64.replace(/^data:image\/\w+;base64,/, '');
    const dataBuffer = new Buffer(base64Data, 'base64');
    fs.writeFile(`data/images/${name}`, dataBuffer, (err) => {
      if (err) {
        res.send(err);
      } else {
        res.send({status: 0 });
      }
    });
  }
複製代碼

4.讀文件

fs.readdirSync(文件名)

@Get('/image/list')
  getProductList(@Res() res): void {
    const data = fs.readdirSync('data/images');
    const url = 'http://localhost:8080/images/';
    res.send({
      data: data.map(item => ({
        name: item,
        id: uuid(),
        src: url + item,
      })),
      status: 0,
    });
  }
複製代碼

5.刪文件

fs.unlinkSync(文件名)

@Get('/image/delete')
  deleteImage(@Query() query, @Res() res): void {
    const files = fs.readdirSync('data/images');
    const target = files.filter(item => item === query.name);
    if (target) {
      fs.unlinkSync('data/images/' + target);
      res.send({status: 0 });
    }
    res.send({status: 1 });
  }
複製代碼

案例

用useEffect代替了didMount請求圖片列表

const [list, setList] = useState([]);

useEffect(() => { 
    getAndUpdateImageList(setList);
},[]);


複製代碼
import React,{useState, useEffect} from 'react';
import UploadImage from "./component/upload-image/upload-image";
import axios from "axios";
import {message} from "antd";

const baseUrl = 'http://localhost:8080/image';

const getImageListUrl = `${baseUrl}/list`;
const addImageUrl = `${baseUrl}/add`;
const deleteImageUrl = `${baseUrl}/delete`;

const ajax = (url, data={}, type='GET') =>{
    return new Promise((resolve)=>{
        const promise = type === 'GET' ? axios.get(url, {params: data}) : axios.post(url, data)
        promise.then(res=>{
            const data = res.data;
            data.status !== 0 ? message.error(data.msg) : resolve(data);
        }).catch(err => {
            message.error('Network request Error: '+err);
        })
    })
};

const getAndUpdateImageList = async(setList) => {
    const data = await ajax(getImageListUrl);
    setList(data.data);
};

const deleteImage = async ({name}, setList)=>{
    await ajax(deleteImageUrl,{name});
    getAndUpdateImageList(setList);
};

const uploadImage = (item, setList) => {
    getAndUpdateImageList(setList);
};

const downloadImage = (item) => {
    console.log('downloadImage', item)
};

function App() {
    const [list, setList] = useState([]);

    useEffect(() => {
        getAndUpdateImageList(setList);
    },[]);

    return (
      <div className="App">
        <UploadImage
            action={addImageUrl}
            list={list}
            onUpload={(item)=>uploadImage(item, setList)}
            onDelete={(item)=>deleteImage(item, setList)}
            onDownload={(item)=>downloadImage(item)}
        />
      </div>
  );
}

export default App;
複製代碼

源碼

github.com/shenleStm/U…

相關文章
相關標籤/搜索