You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
cangku/ck.md

1.7 KiB

package com.ken.wms.common.controller;

import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; /// RHY /**

  • 处理文件下载请求 Spring MVC控制器类用于处理文件下载请求 @PathVariable获取路径中的文件名 HttpServletRequest和HttpServletResponse用于处理请求和响应 */ @Controller @RequestMapping("/commons/fileSource")//指定了基础路径 public class FileSourceHandler {

    @RequestMapping(value = "download/{fileName:.+}", method = RequestMethod.GET)//处理GET请求路径中包含文件名参数使用正则表达式.+匹配带扩展名的文件名 public void fileDownload(@PathVariable("fileName") String fileName, HttpServletRequest request, HttpServletResponse response) throws IOException {

     if (fileName == null)
         return;
    
     // 获取文件
     ServletContext context = request.getServletContext();
     String directory = context.getRealPath("/WEB-INF/download");
     Path file = Paths.get(directory, fileName);
     if (Files.exists(file)) {
         // 设置响应头
         response.addHeader("Content-Disposition", "attachment;filename=" + file.getFileName());
         Files.copy(file, response.getOutputStream());
         response.getOutputStream().flush();
     }
    

    } }