最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

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

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

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

    @ApiOperation("訪問文件")
    @GetMapping("/download/{name}")
    public void getImage(HttpServletResponse response, @PathVariable("name") String name) throws IOException {
        //動(dòng)態(tài)獲取圖片存放位置
        //        String path = getUploadPath();//獲取當(dāng)前系統(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")) {
            //預(yù)覽時(shí)不需設(shè)置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();
    }

注意:踩過的坑,文件名不可以帶*號(hào),帶*會(huì)報(bào)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();
            }

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

            // 返回文件作為響應(yīng)
            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();
        }
    }
}

方法補(bǔ)充

方法一:

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

具體如下

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預(yù)覽,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 {
            //預(yù)覽時(shí)不需設(shè)置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 實(shí)現(xiàn)圖片或文件在線預(yù)覽及下載

完整代碼

@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();
            // 設(shè)置response的Header
            // 解決跨域
            response.addHeader("Access-Control-Allow-Origin", "*");
            boolean b = "jpg".equalsIgnoreCase(fileType) || "png".equalsIgnoreCase(fileType) || "gif".equalsIgnoreCase(fileType);
            // 圖片預(yù)覽
            if (b) {
                response.setContentType("image/" + fileType);
            } else if ("pdf".equalsIgnoreCase(fileType)) {
                // pdf 預(yù)覽
                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();
        }
    }

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

相關(guān)文章

  • 解決SpringMVC、tomcat、Intellij idea、ajax中文亂碼問題

    解決SpringMVC、tomcat、Intellij idea、ajax中文亂碼問題

    這篇文章主要介紹了解決SpringMVC、tomcat、Intellij idea、ajax中文亂碼問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧
    2020-09-09
  • Hibernate實(shí)現(xiàn)many-to-many的映射關(guān)系

    Hibernate實(shí)現(xiàn)many-to-many的映射關(guān)系

    今天小編就為大家分享一篇關(guān)于Hibernate實(shí)現(xiàn)many-to-many的映射關(guān)系,小編覺得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來看看吧
    2019-03-03
  • 淺談java中的TreeMap 排序與TreeSet 排序

    淺談java中的TreeMap 排序與TreeSet 排序

    下面小編就為大家?guī)硪黄獪\談java中的TreeMap 排序與TreeSet 排序。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧
    2016-12-12
  • SpringBoot開發(fā)技巧之使用AOP記錄日志示例解析

    SpringBoot開發(fā)技巧之使用AOP記錄日志示例解析

    這篇文章主要為大家介紹了SpringBoot開發(fā)技巧之如何利用AOP記錄日志的示例解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步
    2021-10-10
  • SpringBoot3整合Druid數(shù)據(jù)源的實(shí)現(xiàn)過程

    SpringBoot3整合Druid數(shù)據(jù)源的實(shí)現(xiàn)過程

    文章介紹了一個(gè)基于Spring?Boot?3的程序?qū)崿F(xiàn)過程,包括創(chuàng)建項(xiàng)目、引入依賴、編寫啟動(dòng)類、配置文件、Controller、啟動(dòng)測(cè)試以及問題解決,本文給大家介紹的非常詳細(xì),感興趣的朋友跟隨小編一起看看吧
    2025-11-11
  • JAVA讀取二進(jìn)制文件以及畫圖教程

    JAVA讀取二進(jìn)制文件以及畫圖教程

    由于項(xiàng)目需要,需要對(duì)二進(jìn)制文件進(jìn)行讀取,所以這篇文章主要給大家介紹了關(guān)于JAVA讀取二進(jìn)制文件以及畫圖的相關(guān)資料,文中通過實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下
    2023-07-07
  • Java深入學(xué)習(xí)圖形用戶界面GUI之布局管理器

    Java深入學(xué)習(xí)圖形用戶界面GUI之布局管理器

    本文章向大家介紹Java GUI布局管理器,主要包括布局管理器使用實(shí)例、應(yīng)用技巧、基本知識(shí)點(diǎn)總結(jié)和需要注意事項(xiàng),具有一定的參考價(jià)值,需要的朋友可以參考一下
    2022-05-05
  • Spring成為Java開發(fā)的標(biāo)準(zhǔn)以及SpringBoot如何徹底改變開發(fā)體驗(yàn)

    Spring成為Java開發(fā)的標(biāo)準(zhǔn)以及SpringBoot如何徹底改變開發(fā)體驗(yàn)

    本文深入剖析了Spring框架及其在Java企業(yè)級(jí)應(yīng)用開發(fā)中的地位,強(qiáng)調(diào)了Spring通過IoC容器、AOP和模塊化生態(tài)系統(tǒng)等核心特性,解決了一系列傳統(tǒng)JavaEE開發(fā)的痛點(diǎn),本文給大家介紹的非常詳細(xì),感興趣的朋友跟隨小編一起看看吧
    2025-12-12
  • request.getParameter()方法的簡單理解與運(yùn)用方式

    request.getParameter()方法的簡單理解與運(yùn)用方式

    在JavaWeb開發(fā)中,request對(duì)象扮演著至關(guān)重要的角色,它是HTTP請(qǐng)求的封裝,request.getParameter()用于獲取客戶端通過GET或POST方式發(fā)送的參數(shù),與之相對(duì),request.setAttribute()用于在服務(wù)器端設(shè)置屬性,這些屬性只在一次請(qǐng)求中有效
    2024-10-10
  • spring?boot集成redisson的最佳實(shí)踐示例

    spring?boot集成redisson的最佳實(shí)踐示例

    這篇文章主要為大家介紹了spring?boot集成redisson的最佳實(shí)踐示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-03-03

最新評(píng)論

武功县| 于田县| 浦北县| 灵寿县| 盐津县| 玉门市| 北辰区| 山阳县| 锡林浩特市| 桃园县| 扎兰屯市| 古蔺县| 阆中市| 奉新县| 禹州市| 上犹县| 凤阳县| 西乌珠穆沁旗| 建平县| 景东| 洞口县| 封开县| 阿鲁科尔沁旗| 嘉荫县| 社会| 正定县| 上饶市| 磐石市| 正宁县| 石台县| 基隆市| 奉节县| 保定市| 淅川县| 顺义区| 蒙山县| 五台县| 嘉禾县| 时尚| 牡丹江市| 台东县|