文件下载/上传

文件下载

 @RequestMapping("download")
    public void download(String fileName, HttpServletRequest req, HttpServletResponse resp) throws IOException {
//        设置响应头  下载:"attachment;filename="+fileName  直接打开:inline
        resp.setHeader("Content-Disposition","attachment;filename="+fileName);
//        输出字符串
//        resp.getWriter().write();
//        输出二进制文件
        ServletOutputStream os = resp.getOutputStream();
        //获取根目录路径
        String filePath = req.getServletContext().getRealPath("files");
        File file = new File(filePath,fileName);
        //将文件转为二进制数组
        byte[] bytes = FileUtils.readFileToByteArray(file);
        os.write(bytes);
        os.flush();
        os.close();
    }

文件上传

Controller

@RequestMapping("upload")
    public String upload(String uname,MultipartFile ufile) throws IOException {
        //获取文件名
        System.out.println(uname);
        String filename = ufile.getOriginalFilename();
        System.out.println(filename);
    //        获取文件名后缀
        String suffix = filename.substring(filename.lastIndexOf("."));
        String uuid = UUID.randomUUID().toString();
        //将 文件流 存到指定路径
        FileUtils.copyInputStreamToFile(ufile.getInputStream(),new File("F:/"+uuid+suffix));
        return "index";
    }	    

jsp

<form action="upload"  enctype="multipart/form-data"  method="post">
姓名:<input type="text" name="uname">
选择文件:<input type="file" name="ufile">
<input type="submit" value="提交">
</form>

springmvc.xml

<!--将上传的二进制文件流转为multifile-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

    <property name="maxUploadSize" value="209715200" />
    <property name="defaultEncoding" value="UTF-8" />
    <property name="resolveLazily" value="true" />
</bean>
  • id="multipartResolver"必须小写
    -public String upload(String uname,MultipartFile ufile)必须和jsp中name相同
enctype属性类型
multipart/form-data当上传二进制文件时,必须改为enctype=“multipart/form-data”
application/x-www-form-urlencoded默认值,小文本传输
text/plain大文本传输
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值