zoukankan      html  css  js  c++  java
  • java模拟调用上传文件接口

    1、模拟调用上传文件接口

    pom

     <dependency>
                <groupId>commons-io</groupId>
                <artifactId>commons-io</artifactId>
                <version>2.4</version>
            </dependency>

    调用方

    @GetMapping("/upload")
        public String upload(String fileName) throws Exception {
            if (StrUtil.isBlank(fileName)) {
                return "fileName is null";
            }
            File file = new File("./src/main/resources/static/uploadFile/");
            if (!file.exists()) {
                file.mkdirs();// 能创建多级目录
            }
            File testFile = new File(file, fileName);
            if (!testFile.exists()) {
                testFile.createNewFile();//有路径才能创建文件
            }
    
            DiskFileItem fileItem = (DiskFileItem) new DiskFileItemFactory().createItem("file",
                    MediaType.TEXT_PLAIN_VALUE, true, testFile.getName());
    
            try {
                InputStream input = new FileInputStream(testFile);
                OutputStream os = fileItem.getOutputStream();
                IOUtils.copy(input, os);
            } catch (Exception e) {
                throw new IllegalArgumentException("Invalid file: " + e, e);
            }
    
            MultipartFile multi = new CommonsMultipartFile(fileItem);
            String s = uploadService.handleFileUpload(multi);
            log.info(s);
            return s;
        }

    被调用方

        @PostMapping(value = "/uploadFile", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
        public String handleFileUpload(@RequestPart(value = "file") MultipartFile file) throws Exception {
            String name = file.getOriginalFilename();
            File filePath = new File("./src/main/resources/static/uploadFile/");
            if (!filePath.exists()) {
                filePath.mkdirs();// 能创建多级目录
            }
            File testFile = new File(filePath, name);
            if (!testFile.exists()) {
                testFile.createNewFile();//有路径才能创建文件
            }
            //第一种 需要绝对路径
    //        file.transferTo(testFile);
            //第二种
            // 使用下面的jar包
            FileUtils.copyInputStreamToFile(file.getInputStream(),testFile);
            return name;
        }
  • 相关阅读:
    查看端口有没有被占用
    微信公众号2()
    How to insert a segment of noise to music file
    puppet practice
    Docker Commands
    LempelZiv algorithm realization
    The algorithm of entropy realization
    Java network programmingguessing game
    Deploy Openstack with RDO and Change VNC console to Spice
    puppet overview
  • 原文地址:https://www.cnblogs.com/super-admin/p/13397672.html
Copyright © 2011-2022 走看看