文件上传和下载

本文介绍了如何在SpringMVC中使用CommonsFileUpload和CommonsIOjar包进行文件上传,包括配置MultipartResolver、Controller处理上传请求和JSP页面的文件选择,以及下载文件的方法和相应的JSP页面设计。
摘要由CSDN通过智能技术生成

1.文件上传

1.1导入jar包

<dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.1</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>

 1.2配置springmvc

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="500000"/>
        <property name="defaultEncoding" value="UTF-8"/>
    </bean>

1.3写Controller中的方法

public class UploadController {
    @RequestMapping(value="/upload",method= RequestMethod.POST)
    public  ModelAndView upload(@RequestParam("file") MultipartFile file, HttpServletRequest request, ModelAndView modelAndView) throws IOException {
        // uploads文件夹位置
        String rootPath = request.getSession().getServletContext().getRealPath("upload");
        // 原始名称
        String originalFileName = file.getOriginalFilename();
        // 新文件
        File newFile = new File(rootPath + File.separator  + File.separator + originalFileName);
        // 判断目标文件所在目录是否存在
        if( !newFile.getParentFile().exists()) {
            // 如果目标文件所在的目录不存在,则创建父目录
            newFile.getParentFile().mkdirs();
        }
        System.out.println(newFile);
        // 将内存中的数据写入磁盘
        file.transferTo(newFile);
        String filePath=newFile.toString();
        //获取相对路径
        String fileName=filePath.substring(filePath.lastIndexOf("\\")+1);
        modelAndView.addObject("url",fileName);
        modelAndView.setViewName("download");
        return modelAndView;
    }

1.4编写jsp页面

<form id="addForm" action="upload" method="post" enctype="multipart/form-data">
        选择文件:<input type="file" name="file" width="120px">
        <input type="submit" value="上传">
    </form>

2.文件下载

2.1Controller中的方法

@RequestMapping("/down")
    public void down(HttpServletRequest request, HttpServletResponse response) throws Exception{
        String filename = request.getParameter("filename");
        System.out.println(filename);
        //模拟文件,myfile.txt为需要下载的文件
        String fileName = request.getSession().getServletContext().getRealPath("upload")+"/"+filename;
        //获取输入流
        InputStream bis = new BufferedInputStream(new FileInputStream(new File(fileName)));
        //假如以中文名下载的话
        // String filename = "下载文件.txt";
        //转码,免得文件名中文乱码
        filename = URLEncoder.encode(filename,"UTF-8");
        //设置文件下载头
        response.addHeader("Content-Disposition", "attachment;filename=" + filename);
        //1.设置文件ContentType类型,这样设置,会自动判断下载文件类型
        response.setContentType("multipart/form-data");
        BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
        int len = 0;
        while((len = bis.read()) != -1){
            out.write(len);
            out.flush();
        }
        out.close();
    }

2.2编写jsp页面

<img src="${pageContext.request.contextPath}/upload/${url}" height="300px" width="300px">

  <div id="upMenu" class="white-content">
      <form id="downForm" lay-filter="updata" action="down" method="get">
          <input type="text" id="filename" name="filename" value="${url}">
          <input type="submit" value="下载">
      </form>
      <input type="button" value="完成">
  </div>

这样我们的一个文件上传下载就完成了

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值