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;
        }
  • 相关阅读:
    HDU 4081 Qin Shi Huang's National Road System
    POJ 2075 Tangled in Cables 最小生成树
    HDU 2487 Ugly window
    UVA 11426 GCD Extrme (Ⅲ)
    POJ_1220_Nmber Sequence
    Fibonacci数列对任何数取模都是一个周期数列
    POJ_3321_APPLE_TREE
    webpack配置---设置快捷打包和浏览器自动刷新
    sublime中css输入分号后自动提示的烦恼
    MongoDB的基本使用
  • 原文地址:https://www.cnblogs.com/super-admin/p/13397672.html
Copyright © 2011-2022 走看看