SSM(spring+springMVC+mybatis)文件上传下载

-上传
–上传前台代码

<input type="file" name="doc">

–后台代码

@RequestMapping("upload")
    public String upload(Integer bid, MultipartFile doc, Model model) {
        BankBean bank = new BankBean();
        if (!doc.isEmpty()) {
            // 获取路径
            String filePath = "D:\\img\\upload\\";
            String originalFilename = doc.getOriginalFilename();
            // UUID随机重命名
            String newFileName = (UUID.randomUUID() + originalFilename
                    .substring(originalFilename.indexOf("."))).replace("-", "");
            // 新文件
            File file = new File(filePath + newFileName);
            // 将文件写入磁盘
            try {
                doc.transferTo(file);
                // 将图片名字写入实体类
                bank = bankService.getBankByBid(bid);
                bank.setFileName(newFileName);
            } catch (IllegalStateException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } else {
            System.out.println("文件为空");
            model.addAttribute("bid", bid);
            // 返回上传页面
            return "upload";
        }
        // 将图片名字写入数据库
        bankService.updateBank(bank);
        // 返回列表页面查看
        return "redirect:getBankList.action";
    }

–前台展示图片代码
—-tomcat展示绝对路径时需要配置如下
在tomcat文件中conf文件夹下server.xml文件中的Host双标签中配置虚拟路径

<Host>
    <Context path="/upload" docBase="D:\img\upload\"  reloadable="true"></Context>
</Host>

–展示/下载前台

<c:if test="${b.fileName != null && b.fileName != '' }">
                        <a href="downLoad.action?fileName=${b.fileName }">
                            <img width="120px" height="80px" src="/upload/${b.fileName }">
                            </a>
</c:if>

–下载后台代码

@RequestMapping("downLoad")
    public ResponseEntity<byte[]> download(String fileName) throws IOException {
        String filePath = "D:\\img\\upload\\";
        File file = new File(filePath + fileName);
        // 处理显示中文文件名的问题
        String newFilename = new String(fileName.getBytes("UTF-8"),
                "iso-8859-1");
        // 设置请求头内容,告诉浏览器代开下载窗口
        HttpHeaders headers = new HttpHeaders();
        headers.setContentDispositionFormData("attachment", newFilename);
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(file),
                headers, HttpStatus.CREATED);
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值