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;
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM