Spring MVC 文件的上传下载

</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>




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值