将图片上传显示浏览器

1.文件上传,通过通道上传文件

/**
     * 文件上传
     * @param request
     * @return
     */
    @PostMapping("/uploadFile")
    @ResponseBody
    public String uploadFiles(@RequestParam("file") MultipartFile file , HttpServletRequest request) throws IOException {
        if (!file.isEmpty()) {
            String saveFileName = file.getOriginalFilename();
            //获取当前路劲的地址
            String systemPath =System.getProperty("user.dir")+"/imageLibrary/";
            String fileName = new Date().getTime()+saveFileName;
            String saveFilePath = systemPath+ fileName;
            //创建文件夹
            File filePath1 = new File(systemPath);
            if (!filePath1.exists()) {
                filePath1.mkdirs();
            }
            //创建文件
            File filePath = new File(saveFilePath);
            if (!filePath.exists()) {
                filePath.createNewFile();
            }

            FileConfig.writeChange(saveFilePath,file);

            return fileName;

        } else {
            return "上传失败,因为文件为空.";
        }

    }
public static void writeChange(String path, MultipartFile file) {

        try {

            File file1 = new File(path);
            RandomAccessFile raf1 = new RandomAccessFile(file1, "rw");
            FileChannel fw = raf1.getChannel();
            ByteBuffer buffer = ByteBuffer.wrap(file.getBytes());
            fw.write(buffer);
            buffer.clear();
            fw.close();
            raf1.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

2.读取文件并且显示到浏览器

 public static void showLogo(String path, HttpServletResponse response){
        try {
            OutputStream os = response.getOutputStream();
            File file1 = new File(path);
            RandomAccessFile raf1 = new RandomAccessFile(file1, "r");
            FileChannel fw = raf1.getChannel();
            ByteBuffer buffer = ByteBuffer.allocate(500);
            while (true){
                buffer.clear();
                int len = fw.read(buffer);

                if (len == -1) {
                    break;
                }
                buffer.flip();
                //也可以通过buffer写
                os.write(buffer.array());
                os.flush();
            }
            os.close();
            fw.close();
            raf1.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值