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;
        }
  • 相关阅读:
    segmentation fault(core dumped)
    (LIS LCS 例题)Max Sum Advanced Fruits Super Jumping! Jumping! Jumping!
    几种数学公式(环排列 母函数 唯一分解定理 卡特兰数 默慈金数 贝尔数 那罗延数)
    map set 详解
    算法录 之 二分和三分
    LIS 最长上升子序列 LCS 最长公共子序列 模板
    JAVA 大数据 例题
    Java 实现大数算法
    7 21 第一次团队赛——————写给队友
    离散化+unique()+二分查找
  • 原文地址:https://www.cnblogs.com/super-admin/p/13397672.html
Copyright © 2011-2022 走看看