下图是我的文件目录:
FileController类
@Controller
@RequestMapping("/file")
public class FileController {
//@RequestParam("file") 把请求中name=file的信息 赋值给CommonsMultipartFile对象
@RequestMapping("/fileupload.do")
public String fileUpload(@RequestParam("file") CommonsMultipartFile file,Model model) throws Exception{
//获取文件名
String fname = file.getOriginalFilename();
System.out.println(fname);
//获取文件后缀
//String suff = fname.substring(fname.lastIndexOf("."));
File ff = new File("F:\\"+fname);
file.getFileItem().write(ff);
/*
* 文件名写入数据库
* 原文件名 新文件名 用户编号
* a.txt 1535012635415.txt 001
* a.txt 1535012635418.txt 002
*/
model.addAttribute("flag", "文件上传成功");
return "/download.jsp";
}
@RequestMapping("/download.do")
public String fileDownload(String fname,HttpServletResponse response) throws Exception{
response.setHeader("Content-Disposition", "attachment;filename="+fname);
File ff = new File("F:\\"+fname);
FileInputStream bis =new FileInputStream(ff);
OutputStream out = response.getOutputStream();
byte [] buff = new byte[1024];
int len = -1;
while((len= bis.read(buff))!=-1){
out.write(buff,0,len);
}
bis.close();
out.close();
return "/upload.jsp";
}
}
以上为正确的访问路径。
这次探讨一下jsp和java代码中的绝对路径和相对路径问题。
如果把@RequestMapping("/fileupload.do")这个方法的返回值从这样return "/download.jsp";变为这样return "download.jsp";那么它的访问路径就变为了springMVCupload/file/download.jsp
而本应访问的地址是http://localhost:8080/springMVCupload/download.jsp。
所以说/是绝对路径,是从项目名开始的;不加/是相对路径是从当前目录开始的,那么问题又来了,请接着看:
如果download.jsp中的代码时这样的
<a href="/file/download.do?fname=up.png">图片</a>访问的路径是这样的
HTTP Status 404 - /file/download.do
而如果写成这样<a href="download.do?fname=up.png">图片</a>
则路径是这样的:http://localhost:8080/springMVCupload/file/download.do?fname=up.png
按道理说第一个和第二个访问的是一样的,但第一个为什么没有成功呢?那是因为第一个少了一个项目名。
那么我们可以总结出:
在jsp中的绝对路径是从端口号,而不是从项目名开始的;在java代码中的路径是以项目名开始的。
绝对路径路径前加/;相对路径不加/,指当前目录。