Java,SpringBoot,Controller,输出本地图片,实现文件下载功能

Java,SpringBoot,Controller,输出本地图片,实现文件下载功能SpringBoot的Controller@RequestMapping支持**配置当Controller配置为:/res,方法配置为:/vie

欢迎大家来到IT世界,在知识的湖畔探索吧!

SpringBoot的Controller

@RequestMapping支持**配置

当Controller配置为:/res,方法配置为:/view/**,可匹配:/res/view/xxxxx,/res/view/xxxxx/xxxxx等。

使用HttpServletResponse中的OutputStream,Controller中方法返回null。

相关内容

Filter实现文件下载功能、Servlet下载文件及视频流

实现的代码案例

Controller类

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Controller
@Api(tags = "文件下载")
@RequestMapping("/res")
@Slf4j
public class CommunalFileDownloadController {

    @Resource
    private ICommunalFileDownloadService communalFileDownloadService;

    @ApiOperation("显示")
    @RequestMapping(value = "/view/**", method = {RequestMethod.GET})
    public R directView(HttpServletRequest request, HttpServletResponse response) {
        log.debug("directView() start");
        log.debug("接收参数,param=");
        R result = null;
        try {
            result = communalFileDownloadService.directView(request, response);
        } catch (Exception e) {
            e.printStackTrace();
            result = R.errMsg(e.getMessage());
        }
        log.debug("响应内容,result=" + result);
        log.debug("directView() end");
        return result;
    }

    @ApiOperation("下载")
    @RequestMapping(value = "/download/**", method = {RequestMethod.GET})
    public R directDownload(HttpServletRequest request, HttpServletResponse response) {
        log.debug("directDownload() start");
        log.debug("接收参数,param=");
        R result = null;
        try {
            result = communalFileDownloadService.directDownload(request, response);
        } catch (Exception e) {
            e.printStackTrace();
            result = R.errMsg(e.getMessage());
        }
        log.debug("响应内容,result=" + result);
        log.debug("directDownload() end");
        return result;
    }

}

欢迎大家来到IT世界,在知识的湖畔探索吧!

Service类

欢迎大家来到IT世界,在知识的湖畔探索吧!import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URLEncoder;

@Service("communalFileDownloadService")
@Slf4j
public class CommunalFileDownloadServiceImpl implements ICommunalFileDownloadService {

    @Override
    public R directView(HttpServletRequest request, HttpServletResponse response) throws Exception {
        log.debug("directView() start");
        // ===================================================================================//
        // ===== 文件路径
        // ===================================================================================//
        String serverStoragePath = SystemThisServer.getServerStoragePath();
        String currentUsePrefix = "/res/view";
        String uri = request.getRequestURI();
        uri = uri.substring(request.getContextPath().length(), uri.length());
        uri = uri.substring(currentUsePrefix.length(), uri.length());
        String filePath = serverStoragePath + uri;
        // ===================================================================================//
        // ===== 设置HTTP头
        // ===================================================================================//
        if (uri.endsWith(".jpg") || uri.endsWith(".jpeg")) {
            response.setContentType("image/jpeg");
        } else if (uri.endsWith(".png")) {
            response.setContentType("image/png");
        } else if (uri.endsWith(".webp")) {
            response.setContentType("image/webp");
        } else if (uri.endsWith(".svg")) {
            response.setContentType("image/svg+xml");
        } else {
            response.setContentType("application/octet-stream");
        }
        // ===================================================================================//
        // ===== 输出文件
        // ===================================================================================//
        ServletOutputStream output = response.getOutputStream();
        InputStream inputStream = new FileInputStream(filePath);
        IOUtils.copy(inputStream, output);
        // ===================================================================================//
        // ===== The end
        // ===================================================================================//
        log.debug("directView() end");
        return null;
    }

    @Override
    public R directDownload(HttpServletRequest request, HttpServletResponse response) throws Exception {
        log.debug("directDownload() start");
        // ===================================================================================//
        // ===== 文件路径
        // ===================================================================================//
        String serverStoragePath = SystemThisServer.getServerStoragePath();
        String currentUsePrefix = "/res/download";
        String uri = request.getRequestURI();
        uri = uri.substring(request.getContextPath().length(), uri.length());
        uri = uri.substring(currentUsePrefix.length(), uri.length());
        String filePath = serverStoragePath + uri;
        // ===================================================================================//
        // ===== 设置HTTP头
        // ===================================================================================//
        File downloadFile = new File(filePath);
        // 制定下载格式和下载文件大小
        response.setContentType("application/octet-stream");
        String downloadName = URLEncoder.encode(downloadFile.getName(), "UTF-8");
        response.setHeader("Content_Length", String.valueOf(downloadFile.length()));
        response.setHeader("Content-Disposition", "attachment; filename=" + downloadName);
        // ===================================================================================//
        // ===== 输出文件
        // ===================================================================================//
        ServletOutputStream output = response.getOutputStream();
        InputStream inputStream = new FileInputStream(filePath);
        IOUtils.copy(inputStream, output);
        // ===================================================================================//
        // ===== The end
        // ===================================================================================//
        log.debug("directDownload() end");
        return null;
    }

}

免责声明:本站所有文章内容,图片,视频等均是来源于用户投稿和互联网及文摘转载整编而成,不代表本站观点,不承担相关法律责任。其著作权各归其原作者或其出版社所有。如发现本站有涉嫌抄袭侵权/违法违规的内容,侵犯到您的权益,请在线联系站长,一经查实,本站将立刻删除。 本文来自网络,若有侵权,请联系删除,如若转载,请注明出处:https://itzsg.com/31671.html

(0)

相关推荐

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

联系我们YX

mu99908888

在线咨询: 微信交谈

邮件:itzsgw@126.com

工作时间:时刻准备着!

关注微信