SpringBoot 文件上传 文件查看

图片上传:

 //TODO 图片上传
    /**
     * 端口号
     */
    @Value("${server.port}")
    private int serverPort;
    private static final Logger logger = Logger.getLogger(DataUser.class);
    /**
     * 文件上传路径
     * 配置文件中 remote.dir=D://img
     */
    @Value("${remote.dir}")
    private String dir;
    /**
     * @Description 文件单个上传
     * @param file
     */
    @ResponseBody
    @RequestMapping(value="/upload")
    public ResponseObject upload(@RequestParam(value="file") MultipartFile file, HttpServletRequest request) {
        try {
            if(file != null) {
                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                String date = format.format(new Date());
                File fileDir = new File(dir+File.separator+date);
                if(!fileDir.exists()) {//文件夹不存在先创建
                    fileDir.mkdirs();
                }
                String code = RandomCodeUtil.getRandomNum(15);
                String suf = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
                file.transferTo(new File(dir+File.separator+date+File.separator+code+suf));
                Map<String, Object> resMap = new HashMap<String, Object>();
                String address = InetAddress.getLocalHost().getHostAddress();
                StringBuffer stringBuffer = new StringBuffer();
                stringBuffer.append("http://").append(address).append(":").append(serverPort)
                        .append("/event/open/api/").append(date).append("/").append(code).append(suf);
//                stringBuffer.append("http://60.216.174.131:8083/event/open/api/").append(date).append("/").append(code).append(suf);
                resMap.put("src", stringBuffer);
                // 服务器
               // return new ResponseObject(0,"上传成功",resMap);
                Map<String, Object> resMap2 = new HashMap<String, Object>();
                StringBuffer url = new StringBuffer();
               // http://localhost:10086/open/api/2021-03-17/026713186045128.jpg
                url.append("http://localhost:10086/open/api/").append(date+"/").append(code).append(suf);
                resMap2.put("src",url);
                return new ResponseObject(0,"上传成功",resMap2);
            }
            return new ResponseObject(500, "文件不能为空", null);
        }catch(Exception e) {
            logger.error(e.getMessage(),e);
            return new ResponseObject(500, "上传失败", null);
        }
    }
//=================================下载 获取文件**
	/**
     * @Description 下载 获取文件
     * @param path
     * @param response
     */
    @RequestMapping(value="/open/api/{date}/{path:.+}")
    public void fetch(@PathVariable String date, @PathVariable String path, HttpServletResponse response) {
        FileInputStream in = null;
        OutputStream out = null;
        try {
            response.setContentType("text/html; charset=UTF-8");
            response.setContentType("image/jpeg");
            in = new FileInputStream(new File(dir+File.separator+date+File.separator+path));
            out = response.getOutputStream();
            byte[] buf = new byte[1024 * 1024 * 10];
            int len;
            while((len = in.read(buf)) != -1) {
                out.write(buf, 0, len);
                out.flush();
            }
            out.close();
        }catch(Exception e) {
            logger.error(e.getMessage(),e);
            e.printStackTrace();
        }finally {
            try {
                if(out != null) {
                    out.close();
                }
                if(in != null) {
                    in.close();
                }
            }catch(IOException e) {
                logger.error(e.getMessage(),e);
                e.printStackTrace();
            }
        }
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值