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;
        }
  • 相关阅读:
    c# web开发
    向wp8开发进军
    练毛笔字的心得
    刚开通博客园
    DevExpress Asp.net(3) ASPxCallback组件
    DevExpress Asp.net(2) ASPxObjectContainer说明
    DevExpress Asp.net(1) ASPxButton的基本使用
    JavaMail学习笔记(四)、使用POP3协议接收并解析电子邮件(全)
    Java正则表达式(一)、抓取网页email地址实例
    JavaMail学习笔记(五)、使用IMAP协议接收并解析电子邮件
  • 原文地址:https://www.cnblogs.com/super-admin/p/13397672.html
Copyright © 2011-2022 走看看