Spring MVC 文件上传下载

package com.zgq.controller;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;



/**
 * 
 * 
 * @Name: FileController.java
 * @Description: 文件操作
 * @Author: 邹国庆
 * @Create 2019年12月24日 上午11:26:47
 */
@Controller
@Scope("prototype")
@RequestMapping("file")
public class FileController {
	@RequestMapping(value="/upFile",method=RequestMethod.POST)
	public String upFile(@RequestParam("file") MultipartFile file,HttpServletRequest req){
		//获取上传路径
		String path = req.getSession().getServletContext().getRealPath("/")+"upFile/"+file.getOriginalFilename();
		//创建目标资源文件
		File target_file = new File(path);
		//上传
		try {
			file.transferTo(target_file);
		} catch (Exception e) {
			e.printStackTrace();
		} 
		return "pages/showView";
	}
	
	/**
	 * 
	 * @Description: TODO
	 * @Author: 邹国庆(作者)
	 * @Create: 2019年12月24日 下午3:01:07
	 * @Parameters: @param file
	 * @Parameters: @param req
	 * @Parameters: @return
	 */
	 private boolean saveFile(MultipartFile file, String path) {  
	        // 判断文件是否为空  
	        if (!file.isEmpty()) {  
	            try {  
	                File filepath = new File(path);
	                if (!filepath.exists()) 
	                    filepath.mkdirs();
	                // 文件保存路径  
	                String savePath = path + file.getOriginalFilename();  
	                
	                // 转存文件  
	                file.transferTo(new File(savePath));  
	                return true;  
	            } catch (Exception e) {  
	                e.printStackTrace();  
	            }  
	        }  
	        return false;  
	    }  
	
	@RequestMapping(value="/upFiles",method=RequestMethod.POST)
    public String upFiles(@RequestParam("files") MultipartFile[] files,HttpServletRequest req) { 
		String path = req.getSession().getServletContext().getRealPath("/")+"upFile/";
        //判断file数组不能为空并且长度大于0  
        if(files!=null&&files.length>0){  
            //循环获取file数组中得文件  
            for(int i = 0;i<files.length;i++){  
                MultipartFile file = files[i];  
                //保存文件  
                saveFile(file, path);  
            }  
        }  
        // 重定向  
        return "pages/showView";
    }  
	
	
	
	/*
	 * 下载方式一:
	 * ①获取前台要下载的文件名称
	 * ②设置响应类型
	 * ③设置下载页显示的文件名
	 * ④获取下载文件夹的绝对路径和文件名合并为File类型
	 * ⑤将文件复制到浏览器
	 */
	@RequestMapping("/download")
	@ResponseBody
	public void download(HttpServletRequest req, HttpServletResponse resp, String filename) throws Exception {
		String realPath =req.getSession().getServletContext().getRealPath("/")+"upFile/";//获取下载文件的路径
		File file = new File(realPath, filename);//把下载文件构成一个文件处理   filename:前台传过来的文件名称
 
		 // filename = new String(filename.getBytes("ISO-8859-1"), "UTF-8");
		//设置响应类型  ==》 告诉浏览器当前是下载操作,我要下载东西
		resp.setContentType("application/x-msdownload");
		//设置下载时文件的显示类型(即文件名称-后缀)   ex:txt为文本类型
		resp.setHeader( "Content-Disposition", "attachment;filename=" + new String( filename.getBytes("gb2312"), "ISO8859-1" ) );
 
		//下载文件:将一个路径下的文件数据转到一个输出流中,也就是把服务器文件通过流写(复制)到浏览器端
		Files.copy(file.toPath(), resp.getOutputStream());//Files.copy(要下载的文件的路径,响应的输出流)
	}

	@RequestMapping("/fileList")
	public String fileList(HttpServletRequest req,HttpSession session) {
		//获取路径
		String filePath =req.getSession().getServletContext().getRealPath("/")+"upFile/";//获取下载文件的路径
		//得到文件夹
		File fp = new File(filePath);
		//取出文件数组数据
		File[]   files = fp.listFiles();
		//定义一个集合存放遍历后的数据
		ArrayList<String> list = new ArrayList<String>();
		for (File f : files) {
			list.add(f.getName());
		}
		session.setAttribute("list", list);
		System.out.println(list);
		 return "pages/showView";
		
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值