myBatis + SpringMVC上传和下载文件

环境:maven+SpringMVC + Spring + MyBatis + MySql

首先要创建数据库,此处使用MySql数据库。
第一步:

导入commons-fileupload-1.3.1.jar和commons-io-2.4.jar以及SpringMVC与Mybatis的整合jar包
注意:文中给出的代码多为节选重要片段,并不齐全。

第二步:

在applicationContext.xml中配置文件上传的bean
    <!-- 配置文件上传 -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize">
            <!-- 最大上传大小:5M -->
            <value>5242880</value>
        </property>
    </bean>

单文件上传
注意:Html中form表单的类型

index.jsp

<!-- 由于上传文件,数据类型是复合类型,所以enctype="multipart/form-data -->
    单文件上传<br/><br/>
    <form action="/springmvc_mybatis_test12_upload/test_upload.action" method="post" enctype="multipart/form-data">
        <input type="file" name="multipartFile">
        <input type="submit" value="上传">
    </form>
控制器Upload_Download.java
//单文件上传,参数必须是MultipartFile类型,用来接收上传的文件
    @RequestMapping("test_upload.action")
    public String test_upload(MultipartFile multipartFile) throws Exception{
        if(!multipartFile.isEmpty()){
            //文件上传的保存路径
            String path="F:\\";
            //图片的原始名称(不含路径)
            String origanlFileName = multipartFile.getOriginalFilename();
            //上传的图片的保存的新名称,随机生成文件名称+.jpg
            String newFileName = UUID.randomUUID()+origanlFileName.substring(origanlFileName.lastIndexOf("."));
            File file = new File(path+newFileName);
            //将内存的数据写到磁盘上
            multipartFile.transferTo(file);
        }
        return "/WEB-INF/jsp/success.jsp";
    }

多文件上传

index.jsp

        <form action="/springmvc_mybatis_test12_upload/test_uploadMoreFile.action" method="post" enctype="multipart/form-data">
            <!-- 上传多个文件,用List<MultipartFile> pic接收 -->
            <input type="file" name="pic[0]"><br/><br/>
            <input type="file" name="pic[1]"><br/><br/>
            <input type="file" name="pic[2]"><br/><br/>
            <input type="file" name="pic[3]"><br/><br/>
            <input type="submit" value="多文件上传">
        </form>
单文件上传时,Controller方法中的参数是MultipartFile类型接收上传的文件的信息,多文件上传时,可以自定义包装类将MultipartFile类型进行包装

MultipartFiles.java

/*
 * 上传多个文件,每个文件都用Controller方法中的MultipartFiles类型的形参接收,所以自定义pojo包装类
 * */
public class MultipartFiles {
    private List<MultipartFile> pic;//用List接收,每个文件对应一个MultipartFile

    public List<MultipartFile> getPic() {
        return pic;
    }

    public void setPic(List<MultipartFile> pic) {
        this.pic = pic;
    }

}

Upload_Download.java

    //多文件上传,MultipartFiles是自定义包装类,用List<MultipartFile>接收
    @RequestMapping("/test_uploadMoreFile.action")
    public String test_uploadMoreFile(MultipartFiles multipartFiles) throws Exception{

        List<MultipartFile> list = multipartFiles.getPic(); //得到上传的文件链表
        for(MultipartFile multipartFile:list){
                     if(!multipartFile.isEmpty()){
                        //上传图片的保存路径
            String path = "F:\\";
            //图片的原始名称(不含路径)
            String origanlFileName = multipartFile.getOriginalFilename();
            //新图片的名称,随机生成文件名称+.jpg
            String newFileName =                     UUID.randomUUID()+origanlFileName.substring(origanlFileName.lastIndexOf("."));
            //新图片
            File file = new File(path+newFileName);
            //将内存中的数据写入磁盘
            multipartFile.transferTo(file);
                    }

        }
        return "/WEB-INF/jsp/success.jsp";
    }

文件下载
Upload_Download.java

//文件下载
    //请求<a href="/springmvc_mybatis_test12_upload/test_download.action?filename=赵奕欢.jpg">点击下载资源</a>
    @RequestMapping("/test_download.action")
    //String filename 是请求参数
    public String test_download(HttpServletRequest request,HttpServletResponse response,String filename) throws Exception{

        filename = new String(filename.getBytes("iso-8859-1"),"UTF-8");//get提交,修改编码

        String path = request.getRealPath("/WEB-INF/picture/"+filename);//得到资源在硬盘上的绝对的路径    
        File file = new File(path);
        response.setCharacterEncoding("UTF-8");
        filename = URLEncoder.encode(filename, "UTF-8");//将中文转为浏览器可认识的编码
        response.setHeader("content-disposition", "attachment;filename="+filename);//设置响应头为文件下载
        response.setContentLength((int)file.length());
        int len = 0;
        byte []buffer = new byte[1024];
        InputStream is = new FileInputStream(file);
        OutputStream os= response.getOutputStream();//向浏览器写数据
        while((len = is.read(buffer)) != -1){
            os.write(buffer,0,len);
        }
        is.close();
        os.close();
        return null;    //一定要返回null,执行后不跳转
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值