欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Java實現(xiàn)文件圖片的預覽和下載功能

 更新時間:2025年04月03日 11:12:58   作者:小徐敲java  
這篇文章主要為大家詳細介紹了如何使用Java實現(xiàn)文件圖片的預覽和下載功能,文中的示例代碼講解詳細,感興趣的小伙伴可以跟隨小編一起學習一下

Java實現(xiàn)文件(圖片)的預覽和下載

    @ApiOperation("訪問文件")
    @GetMapping("/download/{name}")
    public void getImage(HttpServletResponse response, @PathVariable("name") String name) throws IOException {
        //動態(tài)獲取圖片存放位置
        //        String path = getUploadPath();//獲取當前系統(tǒng)路徑
        String path = upload;
        String imagePath = path + File.separator + name;
        if (!new File(imagePath).exists()) {
            return;
        }
        if (name.endsWith("jpg") || name.endsWith("png") || name.endsWith("gif") || name.endsWith("jpeg")) {
            //預覽時不需設置Content-Disposition
            response.setContentType("image/jpeg;charset=utf-8");//圖片
        }else {
            //下載
        response.setContentType("application/octet-stream");//文件
        response.setHeader("Content-Disposition", "inline; filename=" + URLEncoder.encode(name, "UTF-8"));
        }
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(Files.readAllBytes(Paths.get(path).resolve(name)));
        outputStream.flush();
        outputStream.close();
    }

注意:踩過的坑,文件名不可以帶*號,帶*會報java.io.FileNotFoundException

通過mvc與hutool工具集下載在resources目錄下的文件,注意引入的包

package com.example.controller;

import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.nio.file.Files;

@RestController
@RequestMapping("/api/files")
public class FileDownloadController {

    @GetMapping("/download")
    public ResponseEntity<Resource> downloadFile() {
        String fileName = "example.txt"; // 要下載的文件名
        
        try {
            // 從 resources 目錄加載文件
            ClassPathResource resource = new ClassPathResource(fileName);
            
            if (!resource.exists()) {
                return ResponseEntity.notFound().build();
            }

            // 設置響應頭
            HttpHeaders headers = new HttpHeaders();
            headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + resource.getFilename());

            // 返回文件作為響應
            return ResponseEntity.ok()
                    .headers(headers)
                    .contentType(org.springframework.http.MediaType.APPLICATION_OCTET_STREAM)
                    .body(resource);
        } catch (IOException e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
        }
    }
}

方法補充

方法一:

該代碼段展示了如何在Spring Boot中實現(xiàn)文件的預覽和下載功能。通過HttpServletRequest和HttpServletResponse,根據(jù)請求參數(shù)判斷是預覽還是下載,并設置相應的內容類型和Content-Disposition。文件路徑為固定目錄下,讀取文件內容并寫入響應流。

具體如下

package com.example.demo.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;

/**
 * @author long
 * @version 1.0.0
 * @ClassName FileController
 * @Description TODO
 * @createTime 2022.03.18 18:47
 */
@RestController
@RequestMapping("/demo")
public class FileController {


    @GetMapping("/file")
    public void filePreviewOrDownload(HttpServletRequest request, HttpServletResponse response) throws Exception {
        String fileName = request.getParameter("fileName");
        //type. p預覽,d下載
        String type = request.getParameter("type");
        response.reset();
        response.setCharacterEncoding("UTF-8");

        File file = new File("C:\\Users\\long\\Desktop\\" + fileName);
        FileInputStream fis = new FileInputStream(file);

        if ("d".equalsIgnoreCase(type)) {
            //下載
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename*=utf-8''" + System.currentTimeMillis() + fileName.substring(fileName.lastIndexOf(".")));

        } else {
            //預覽時不需設置Content-Disposition
//            response.setContentType("application/octet-stream");
//            response.setContentType("text/html;charset=UTF-8");
//            response.setHeader("Content-Disposition","inline;filename=" + System.currentTimeMillis() + fileName.substring(fileName.lastIndexOf(".")));
        }
        OutputStream os = response.getOutputStream();
        byte[] bytes = new byte[1024];
        int length = 0;
        while ((length = fis.read(bytes)) != -1) {
            os.write(bytes, 0, length);
        }
        os.close();
        fis.close();
    }


}

方法二:

Java 實現(xiàn)圖片或文件在線預覽及下載

完整代碼

@GetMapping("/downFile")
    public void downFile(HttpServletResponse response, HttpServletRequest request) {
        try {
//            File file = new File("C:\\Users\\hnsh\\Pictures\\鐵山靠.png");
            File file = new File("F:\\BaiduNetdiskDownload\\activiti教程 (1).pdf");
            String filename = file.getName();
            String fileType = filename.substring(filename.indexOf(".") + 1);

            // 以流的形式下載文件。
            FileInputStream fileInputStream = new FileInputStream(file);
            InputStream fis = new BufferedInputStream(fileInputStream);
            byte[] buffer = new byte[1024];
            int len = 0;
            // 清空response
            response.reset();
            // 設置response的Header
            // 解決跨域
            response.addHeader("Access-Control-Allow-Origin", "*");
            boolean b = "jpg".equalsIgnoreCase(fileType) || "png".equalsIgnoreCase(fileType) || "gif".equalsIgnoreCase(fileType);
            // 圖片預覽
            if (b) {
                response.setContentType("image/" + fileType);
            } else if ("pdf".equalsIgnoreCase(fileType)) {
                // pdf 預覽
                response.setContentType("application/pdf");
            } else {
                // 直接下載
                response.setContentType("application/text;chartset=utf-8");
                response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
                response.addHeader("Content-Length", "" + file.length());
            }
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            int a = 0;
            while ((len = fis.read(buffer)) != -1) {
                a = len + a;
                toClient.write(buffer, 0, len);
            }
            toClient.flush();
            toClient.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

到此這篇關于Java實現(xiàn)文件圖片的預覽和下載功能的文章就介紹到這了,更多相關Java圖片預覽和下載內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

  • 詳細介紹MyBatis 3.4.0版本的功能

    詳細介紹MyBatis 3.4.0版本的功能

    這篇文章主要給大家介紹了關于MyBatis 3.4.0版本的功能,文中只列舉部分重要的內容,詳細內容看官方說明,需要的朋友可以參考借鑒,下面跟著小編一起來學習學習吧。
    2017-06-06
  • java org.springframework.boot 對redis操作方法

    java org.springframework.boot 對redis操作方法

    在Spring Boot項目中操作Redis,你可以使用Spring Data Redis,Spring Data Redis是Spring提供的一個用于簡化Redis數(shù)據(jù)訪問的模塊,它提供了一個易于使用的編程模型來與Redis交互,本文給大家介紹java org.springframework.boot 對redis操作方法,感興趣的朋友一起看看吧
    2025-04-04
  • Java 正則表達式 解釋說明

    Java 正則表達式 解釋說明

    java正則知識小結,一些常見的正則都包括在里面,推薦收藏。
    2009-06-06
  • Java為什么使用補碼進行計算的原因分析

    Java為什么使用補碼進行計算的原因分析

    這篇文章主要介紹了Java為什么使用補碼進行計算的原因分析,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2020-08-08
  • Java基礎類之ArrayUtils工具類詳解

    Java基礎類之ArrayUtils工具類詳解

    這篇文章主要介紹了java.ArrayDeque類使用方法,java.ArrayDeque類提供了可調整大小的陣列,并實現(xiàn)了Deque接口,感興趣的小伙伴們可以參考一下
    2021-09-09
  • Java中Excel高效解析工具EasyExcel的實踐

    Java中Excel高效解析工具EasyExcel的實踐

    EasyExcel是阿里巴巴開源的一個excel處理框架,已使用簡單,節(jié)省內存著稱,下面這篇文章主要給大家介紹了關于Java中Excel高效解析工具EasyExcel實踐的相關資料,需要的朋友可以參考下
    2022-04-04
  • Java判斷2個List集合是否相等(不考慮元素的順序)

    Java判斷2個List集合是否相等(不考慮元素的順序)

    今天小編就為大家分享一篇關于Java判斷2個List集合是否相等(不考慮元素的順序)的文章,小編覺得內容挺不錯的,現(xiàn)在分享給大家,具有很好的參考價值,需要的朋友一起跟隨小編來看看吧
    2018-10-10
  • Springboot中的異步任務執(zhí)行及監(jiān)控詳解

    Springboot中的異步任務執(zhí)行及監(jiān)控詳解

    這篇文章主要介紹了Springboot中的異步任務執(zhí)行及監(jiān)控詳解,除了自己實現(xiàn)線程外,springboot本身就提供了通過注解的方式,進行異步任務的執(zhí)行,下面主要記錄一下,在Springboot項目中實現(xiàn)異步任務,以及對異步任務進行封裝監(jiān)控,需要的朋友可以參考下
    2023-10-10
  • java實現(xiàn)微信掃碼支付功能

    java實現(xiàn)微信掃碼支付功能

    這篇文章主要為大家詳細介紹了java實現(xiàn)微信掃碼支付功能,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2018-07-07
  • 在SpringBoot當中使用Thymeleaf視圖解析器的詳細教程

    在SpringBoot當中使用Thymeleaf視圖解析器的詳細教程

    Thymeleaf是一款開源的模板引擎,它允許前端開發(fā)者使用HTML與XML編寫動態(tài)網(wǎng)頁,hymeleaf的主要特點是將表達式語言嵌入到HTML結構中,它支持Spring框架,使得在Spring MVC應用中集成非常方便,本文給大家介紹了在SpringBoot當中使用Thymeleaf視圖解析器的詳細教程
    2024-09-09

最新評論