您的位置:首页 > 编程语言 > Java开发

Spring MVC 文件的上传下载

2014-11-18 13:42 274 查看
</pre><p><pre name="code" class="java">
/**
* 上传文件
* @param req 请求
* @param file 文件
* @return URL路径
*/
@RequestMapping("/upload")
public String upload(HttpServletRequest req,@RequestParam("file") MultipartFile file){

//路径
String path = req.getSession().getServletContext().getRealPath("/WEB-INF/file");

//判断文件
if(!file.isEmpty()){
//上传的文件袋的名称
String oldName = file.getOriginalFilename();
//取文件名的后缀
String suffix = oldName.substring(oldName.lastIndexOf("."));
//改变文件的名称
String newName = UUID.randomUUID() + toString() + suffix;
//将更改的文件名存放在session
req.getSession().setAttribute("fileName", newName);
File f = new File(path + "/" + newName);
try {
//通过封装好的方法将文件上传到指定的文件夹
file.transferTo(f);
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

return "redirect:/console/year/all";
}

/**
* 下载文件
* @param fileName 文件名
* @param req 请求
* @param resp 响应
*/
@RequestMapping("/downfile")
public void downFile(@RequestParam("fileName")String fileName,HttpServletRequest req, HttpServletResponse resp){
InputStream in = null;
OutputStream out = null;

//路径
String path = req.getSession().getServletContext().getRealPath("/WEB-INF/file");
//设置请求头
resp.setHeader("content-disposition", "ATTCHMENT;fileName="+fileName);
try {
//创建流
in = new FileInputStream(new File(path + "/" + fileName));
out = resp.getOutputStream();
byte [] bytes = new byte[512];
int total = 0;
//写 读多少写多少
while((total = in.read(bytes)) != -1){
out.write(bytes, 0, total);
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
try {
in.close();
out.close();
} catch (IOException e) {
e.printStackTrace();
}

}
}
页面 from表单必须有enctype="multipart/form-data" 属性才能进行上传文件
<div>
<form action="${ctx}/console/year/upload"  method="post"  enctype="multipart/form-data" >
<table>
<tr>
<td>添加附件</td>
<td>
<input type="file" name="file" id="file"/>
</td>
</tr>
<tr>
<td>
<input type="submit" value="提交"/>
</td>
</tr>
</table>
</form>
<table>
<tr>
<th>附件</th>
<td>${fileName}<a href="${ctx}/console/year/downfile?fileName=${fileName}">下载</a></td>
</tr>
</table>
</div>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java spring mvc