zoukankan      html  css  js  c++  java
  • java接收图片的两种方法

    1、使用http接收IO流

    2、使用接收formdata表单的方式

    controller:

        @PostMapping("savePicByIo")
        public String savePicByIo(HttpServletRequest request) throws Exception{
            System.out.println("图片上传开始");
            String fileName = savePictureService.savePicByIo(request);
            return fileName;
        }
    
        @PostMapping("savePicByFormData")
        public String savePicByFormData(@RequestParam("file")MultipartFile file) throws IOException {
            String fileName = savePictureService.savePicByFormData(file);
            return fileName;
        }

    service:

        public String savePicByIo(HttpServletRequest request) throws IOException {
            // 图片存储路径
            String path = "C:\image\factory";
            // 判断是否有路径
            if (!new File(path).exists()) {
                new File(path).mkdirs();
            }
            ServletInputStream inputStream = request.getInputStream();
            String fileName = UUID.randomUUID().toString().replace("-","") + ".jpg";
            File tempFile = new File(path,fileName);
            if (!tempFile.exists()) {
                OutputStream os = new FileOutputStream(tempFile);
                BufferedOutputStream bos = new BufferedOutputStream(os);
                byte[] buf = new byte[1024];
                int length;
                length = inputStream.read(buf,0,buf.length);
                while (length != -1) {
                    bos.write(buf, 0 , length);
                    length = inputStream.read(buf);
                }
                bos.close();
                os.close();
                inputStream.close();
            }
            return fileName;
        }
    
    
        public String savePicByFormData(MultipartFile file) throws IOException {
    
            // 图片存储路径
            String path = "C:\image\factory";
            // 判断是否有路径
            if (!new File(path).exists()) {
                new File(path).mkdirs();
            }
            String fileName = UUID.randomUUID().toString().replace("-","") + ".jpg";
            File tempFile = new File(path,fileName);
            if (!tempFile.exists()) {
                tempFile.createNewFile();
            }
            file.transferTo(tempFile);
            return fileName;
        }
  • 相关阅读:
    Android(java)学习笔记15:匿名内部类实现多线程
    Android(java)学习笔记14:Java线程池
    Android(java)学习笔记13:线程组的概述和使用
    Android(java)学习笔记12:线程的状态转换图以及常见执行情况
    win2012R2打Windows8.1-KB2919355 问题
    win2012R2打Windows8.1-KB2919355 问题
    P2404
    P2404
    P2404
    抽签
  • 原文地址:https://www.cnblogs.com/flypig666/p/12488556.html
Copyright © 2011-2022 走看看