1. 程式人生 > 資料庫 >redis 實現圖片上傳下載demo

redis 實現圖片上傳下載demo

1:依賴包:
<!--    JSON依賴包-->
       <dependency>
           <groupId>com.alibaba</groupId>
           <artifactId>fastjson</artifactId>
           <version>1.2.28</version>
       </dependency>

  

2:圖片編解碼工具類
import sun.misc.BASE64Encoder;
import sun.misc.BASE64Decoder;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;

/**
 * @version 1.0
 * @name 
 * @date 2020/11/6 16:12
 * @function 圖片編解碼工具類
 */
public class EncodeImgUtil
{
    /**
     * @author
     *  將圖片內容處理成Base64編碼格式
     * @version 1.0
     */
    public static String encoderImg(MultipartFile file ){
        String imgString  = null;
        byte[] imgBytes = null;

        try{
            //將圖片轉化為位元組陣列
            imgBytes = file.getBytes();
        }catch (Exception e){
            e.printStackTrace();
        }

        //將圖片位元組陣列進行Base64編碼
        BASE64Encoder encoder = new BASE64Encoder();
        imgString = encoder.encode(imgBytes);
        return imgString;
    }

    /**
     * @author 將圖片內容處理成Base64解碼格式
     *  將圖片解碼 imgString 圖片Base64編碼格式
     * @version 1.0
     */
    public static byte[] decoderImg(String imgString)throws IOException
    {
        byte[] imgBytes = null;
        BASE64Decoder base64Decoder = new BASE64Decoder();
        imgBytes = base64Decoder.decodeBuffer(imgString);
        return imgBytes;

    }

}

  

3:頁面:
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>圖片上傳</title>
    <script src="../js/jquery.js"></script>

    <script>
        $(function () {
            $("#btn").click(function () {
                var formData = new FormData();
                var file = $("#file")[0].files[0];
                formData.append("file",file);

                $.ajax({
                    url:"/user/upload",
                    type:"post",
                    data:formData,
                    processData: false, //使資料不做處理
                    contentType:false, //不要設定請求頭
                    success:function (result) {
                            if(result == "OK"){
                                alert("上傳成功")
                            }else{
                                alert("上傳失敗")
                        }
                    }
                })


            })

            $("#btn2").click(function () {
                    $.ajax({
                        url:"/user/download",
                        type:"post",
                        dataType:"json",
                        data: {"name":$("#name").val()},
                        success:function (data) {
                           // alert(data);
                            if(data =="fail"){
                                alert("下載圖片失敗")
                            }else{
                                //將圖片顯示在img中
                                $("#ImgePic").attr("src","data:image/png;base64,"+data)
                            }

                        }
                    })
            })
        })
    </script>
</head>
<body>
<!--上傳圖片-->
<input type="file" name="file" id="file"/><br/>
<input type="button" id="btn" value="上傳圖片"/><br/>

<!--下載圖片-->
<input type="text" id="name" name="name"/><br/>
<input type="button" id="btn2" value="下載圖片"/><br/>
<img id="ImgePic" src="ImgePic" width="800" height="600"/><br/>
</body>
</html>

  4:controller

import com.alibaba.fastjson.JSON;
import com.dtone.ssm.redis.RedisUtil;
import com.dtone.ssm.util.EncodeImgUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import java.io.IOException;
import java.util.UUID;

/**
 * @version 1.0
 * @name
 * @date 2020/11/6 16:38
 * @function 圖片上傳/下載頁面請求控制器類
 */
@RestController
@Slf4j // Lombok 外掛建立 Logger 日誌物件
public class ImgController
{
    @Autowired
    private RedisUtil redisUtil;


    @RequestMapping("user/upload")
    public String upload(MultipartFile file){
        log.info("收到upload請求");

        //獲取檔名
        String fileName = file.getOriginalFilename();

        //隨機生成唯一ID
       // String uuid = UUID.randomUUID().toString();

        //將檔案轉化為Base64編碼格式
       String imgString = EncodeImgUtil.encoderImg(file);

       //將檔案儲存到redis
        if(redisUtil.exists(fileName)){
            return "fail";
        }
        redisUtil.set(fileName,imgString);
        return "OK";

    }

    @RequestMapping("user/download")
    public String download(String name) throws IOException {
        log.info("收到user/dpwnload請求"+name);

        if(name !=null){
            //從redis獲取Base64為編碼格式
            String imgString  = (String) redisUtil.get(name);

            //將Base64編碼格式圖片轉化為位元組陣列
            byte[] imgBytes = EncodeImgUtil.decoderImg(imgString);

            //將圖片位元組陣列轉化為JSON格式傳送給客戶端
            return JSON.toJSONString(imgBytes);
        }
        return "fail";


    }
}