文件下载使用restful风格时的status:404

文件下载使用restful风格时的status:404

404场景:
前台通过url传值时使用restful风格

<th><a href="fileDownLoad/${stu.filename}/${stu.filetype}">下载</a></th>

后台接收方式:

 @RequestMapping("/fileDownLoad/{filename}/{filetype1}/{filetype2}")
  public void fileDownLoad(@PathVariable String filename,@PathVariable String filetype, HttpServletRequest req, HttpServletResponse resp) throws Exception{
    
    
 		
 		//验证传值信息
        System.out.println(filename + "-----------" + filetype);

        //把需要下载的文件从服务器读过来
        String realPath = req.getServletContext().getRealPath("/upload");
        File file = new File(realPath + "/" + filename);
        InputStream inputStream = new FileInputStream(file);

//        设置属性下载到本地
//        设置下载文件的长度
        resp.setContentLength((int) file.length());

//         设置下载文件的类型
        resp.setContentType(filetype);

//        设置响应头信息
        resp.setHeader("Content-Disposition","attachment;filename=" + filename);

        //把读取的文件写到本地
        OutputStream outputStream = resp.getOutputStream();
        IOUtils.copy(inputStream,outputStream);

        outputStream.close();
        inputStream.close();

    }

输出验证:
System.out.println(filename + “-----------” + filetype);

8762a55b-80bd-47bb-b1ed-992f29751a66.jpg-----------image/jpeg

可知 filetype 的值为 image/jpeg

然而我们的获取方式:

public void fileDownLoad(@PathVariable String filename,@PathVariable String filetype, HttpServletRequest req, HttpServletResponse resp) throws Exception{
    
    

@PathVariable String filetype = image

正解:

public void fileDownLoad(@PathVariable String filename,@PathVariable String filetype1,@PathVariable String filetype2, HttpServletRequest req, HttpServletResponse resp) throws Exception{
    
    
    //public void fileDownLoad(String filename,String filetype, HttpServletRequest req,HttpServletResponse resp) throws Exception{
    
    
	String filetype = filetype1 + "/" +filetype2;

使用常规get方式:

前台:

<th><a href="fileDownLoad?filename=${
    
    stu.filename}&filetype=${
    
    stu.filetype}">下载</a></th>

后台:

@RequestMapping("fileDownLoad")
public void fileDownLoad(String filename,String filetype, HttpServletRequest req,HttpServletResponse resp) throws Exception{
    
    

猜你喜欢

转载自blog.csdn.net/weixin_44192389/article/details/106976402