上传文件和写入文件

上传文件到本地

1.页面写法

<input type="file" name="photofile" id="photo" />

 <form id="appForm" action="#springUrl('/')apps/update" method="post" enctype="multipart/form-data">

2.后台接受

@RequestParam(value = "photofile", required = false) MultipartFile photofile,

转换存入本地

//文件路径和文件名字

 File file = new File(imgDir, filename);
//转化为file
        if (null != multipartFile && !multipartFile.isEmpty()) {
            multipartFile.transferTo(file);
        }

分割文件路径的时候要注意File.separator
windows是\或/,unix是/ 使用File.separator完美解决
3.页面回显

<img src="#springUrl('/')apps/getPhoto/${app.id}" width="110" height="80" />
String img = null;
        OutputStream os = null;
        FileInputStream fis = null;
        try {
            response.setHeader("Pragma", "no-cache");
            response.setHeader("Cache-Control", "no-cache");
            response.setDateHeader("Expires", 0);
            App app = sqlSession.selectOne(
                    "com.itrus.portal.db.AppMapper.selectByPrimaryKey", id);

            if (null == app) {
                return "status403";
            }
            img = app.getAppIcon();
            if (img == null) {
                return "status403";
            }
            //获得文件路径和名字
            File filePath = appService.getFilePathById(id);
            if (!filePath.exists()) {
                filePath.mkdir();
            }
            File file = new File(filePath, img);

            fis = new FileInputStream(file);
            byte[] bb = IOUtils.toByteArray(fis);
            os = response.getOutputStream();
            os.write(bb);
            os.flush();
        } catch (IOException e) {// 未找到
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {// 关闭流!
            try {
                if (null != fis) {
                    fis.close();
                }
                if (null != os) {
                    os.close();
                }
            } catch (IOException e) {
            }
        }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值