1. 程式人生 > >SpringMVC實現文件下載時,請求路徑中的擴展名被省略

SpringMVC實現文件下載時,請求路徑中的擴展名被省略

springmvc oca spring -- localhost 存在 name map 瀏覽器

問題描述

  問題是這樣的,我寫了一個DownloadController,用來處理下載請求,預期效果如下:

  客戶端瀏覽器在訪問URL --> http://localhost:8080/ssm/download/demo.txt,就會下載demo.txt文件。

  代碼如下:

@Controller
public class DownloadController {

	@RequestMapping("/download/{fileName}")
	public String download(@PathVariable String fileName, HttpServletRequest req, HttpServletResponse resp) {

		String downloadDir = "/var/work/download";
		File targetFile = new File(downloadDir, fileName);

		if (! targetFile.exists()) {
			req.setAttribute("msg", "文件不存在,路徑:" + targetFile.getAbsolutePath());
			return "error";
		}

		// .....省略了剩余代碼
	}
}

  啟動服務器之後,訪問上面這個路徑:http://localhost:8080/ssm/download/demo.txt,原本以為會立即下載文件demo.txt,但是卻顯示:文件不存在,路徑:/var/work/download/demo。

  於是我打印了一下接收到的fileName參數,發現打印的是“demo”,而不是“demo.txt”。

解決方式

  將@RequestMapping註解的value修改一下,使用SpEL即可:

@RequestMapping("/download/{fileName:.+}")

  這樣就不會省略請求路徑中的文件名了。

  

SpringMVC實現文件下載時,請求路徑中的擴展名被省略