Spring MVC 文件上传下载功能

action层文件:

package com.jfkj.action;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

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

import org.apache.commons.io.FileUtils;
import org.springframework.context.annotation.Scope;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

@Controller
@Scope("prototype")
@RequestMapping("/uplond")
public class upAndDown {
    //单个文件上传
    @RequestMapping("/fileup")
    public ModelAndView fileup(@RequestParam(value="file") MultipartFile flie
            ,HttpServletRequest request){
        //获取文件存放路径
        File filepath = new File(request.getSession().getServletContext().getRealPath("/")+    "files/");
        //判断当前文件夹是否存在,不存在就创建
        if(!filepath.exists()){
            filepath.mkdir();
        }
        //获取上传文件的路径
        String path = request.getSession().getServletContext().getRealPath("/")+"files/"+flie.getOriginalFilename();
        //通过路径获得文件类
        File upfile = new File(path);
        //保存
        try {
            flie.transferTo(upfile);
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //设置跳转页面
        ModelAndView mv = new ModelAndView("t1");
        //跳转
        return mv;
    }
    //多个文件上传
    @RequestMapping("/fileups")
    public ModelAndView fileups(@RequestParam(value="file") MultipartFile[] flies
            ,HttpServletRequest request) throws IOException{
        //获取文件存放路径
        File filepath = new File(request.getSession().getServletContext().getRealPath("/")+    "files/");
        //判断当前文件夹是否存在,不存在就创建
        if(!filepath.exists()){
            filepath.mkdir();
        }
        //判断是否有文件上传上来
        if(flies != null && flies.length>0){
            for (int i = 0; i < flies.length; i++) {
                 MultipartFile file = flies[i];
                //获取上传文件的路径
                 String path = request.getSession().getServletContext().getRealPath("/")+"files/"+file.getOriginalFilename();
                //通过路径获得文件类
                File upfile = new File(path);
                //保存
                try {
                    file.transferTo(upfile);
                } catch (IllegalStateException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        //设置跳转页面
        ModelAndView mv = new ModelAndView("t1");
        //跳转
        return mv;
    }
    
    //显示文件列表
    @RequestMapping("/showfile")
    public ModelAndView showfile(HttpServletRequest request){
        File filepath = new File(request.getSession().getServletContext().getRealPath("/")+    "files/");
        File[] file =  filepath.listFiles();
        List names = new ArrayList();
        for (File files : file) {
            names.add(files.getName());
        }
        ModelAndView mv = new ModelAndView("show");
        mv.addObject("filesname", names);
        return mv;
        
    }
    
    //文件下载
    @RequestMapping("/down")
    public ResponseEntity<byte[]> down(HttpServletRequest request) throws IOException{
        //获得要返回的文件
        File file = new File(request.getSession().getServletContext().getRealPath("/")+    "files/"+request.getParameter("file"));
        //设置文件名中文编码
        String dfileName = new String(request.getParameter("file").getBytes("gb2312"), "iso8859-1");  
        //创建返回头信息对象
        HttpHeaders header = new HttpHeaders(); 
        //设置返回头
        header.setContentType(MediaType.APPLICATION_OCTET_STREAM); 
        header.setContentDispositionFormData("attachment", dfileName); 
        //返回文件流对象
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file), header, HttpStatus.CREATED); 
    }
}

 

网页访问代码:

<label>单个文件上传</label>
    <form action="${pageContext.request.contextPath }/uplond/fileup" method="post"  enctype="multipart/form-data">
        <input type="file" name="file"/><br>
        <button type="submit">上!!!传!</button>
    </form>

<br> <br> <br> <label>多个个文件上传</label> <form action="${pageContext.request.contextPath }/uplond/fileups" method="post" enctype="multipart/form-data"> <input type="file" name="file"/><br> <input type="file" name="file"/><br> <input type="file" name="file"/><br> <input type="file" name="file"/><br> <button type="submit">上!!!传!</button> </form>

<br> <br> <br> <label>进入文件展示列表,点击可下载</label> <a href="${pageContext.request.contextPath }/uplond/showfile">点击显示文件列表</a>

点击显示文件列表后显示文件别表页面代码:

 <body>
      <c:forEach items="${filesname }" var="item">
          <a href="${pageContext.request.contextPath }/uplond/down?file=${item }">${item }</a> <br>
      </c:forEach>
  </body>

 

posted @ 2019-05-24 12:05  细竹赫映姬  阅读(148)  评论(0)    收藏  举报