axios+springboot實現圖片預覽(POST方式)

相關文章:
axios+springboot實現文件上傳(文件以及表單)、下載(post/get方式)


簡介

圖片實際上就是圖片下載功能

實現

①後端下載邏輯
就是接收前臺傳過來的文件名fileName,找到對應的文件返回給前臺

@RequestMapping("/download")
public ResponseEntity<Object> downloadFile3(@RequestBody String fileName) {
    return downloadFile(fileName);
}

private ResponseEntity<Object> downloadFile(String fileName){
    String parentPath = getParentPath();
    File file = new File(parentPath, fileName);
    InputStreamResource resource = null;
    try {
        resource = new InputStreamResource(new FileInputStream(file));
    } catch (Exception e) {
        e.printStackTrace();
    }
    HttpHeaders headers = new HttpHeaders();
    headers.add("Content-Disposition", String.format("attachment;filename=\"%s", fileName));
    headers.add("Cache-Control", "no-cache,no-store,must-revalidate");
    headers.add("Pragma", "no-cache");
    headers.add("Expires", "0");
    ResponseEntity<Object> responseEntity = ResponseEntity.ok()
            .headers(headers)
            .contentLength(file.length())
            .contentType(MediaType.parseMediaType("application/octet-stream"))
            .body(resource);
    return responseEntity;
}

②前端代碼:
因爲是post請求,axios接收到的其實是二進制,這時候需要加上data:image/png;base64,前綴進行Base64編碼,就可以正常顯示了

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div id="uploadApp">

    <span>{{ saveFileName }}</span>
    <br/><br/><br/>
    <button @click="goPreview" style="width: 80px;height: 30px;">圖片預覽</button>

    <div id="imgShowModal" style="margin-left: 0;display: none;">
        <img :src="showImg">
    </div>

</div>

<script src="/js/public/jquery-3.4.1.min.js"></script>
<script src="/js/public/vue.min.js"></script>
<script src="/js/public/axios.min.js"></script>

<script>
    let app = new Vue({
        el: '#uploadApp',
        data: {
            bean: {},
            saveFileName: 'test.png',//要下載的文件名
            showImg: ''
        },
        methods: {
            goPreview: () => {
                axios({
                    method: "POST",
                    url: "/download",
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    data: app.saveFileName,
                    responseType: 'arraybuffer'//注意這裏的類型
                }).then(response => {
                	//post接收到的字符串,這裏要轉換
                    return 'data:image/png;base64,' + btoa(new Uint8Array(response.data).reduce((data, byte) => data + String.fromCharCode(byte), ''));
                }).then(data => {
                    app.showImg = data;
                    $('#imgShowModal').show();
                });
            }
        }
    })
</script>
</body>
</html>

③效果展示:
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章