zoukankan      html  css  js  c++  java
  • 004 springboot文件上传

      关于文件上传,在spring cloud会再经过配置文件的处理,在spring boot则不需要,在这里写一个文件上传的接口。

      单文件上传,如果以后写多文件上传再进行补充。

    1.文件目录

      

    2.控制器程序

    package com.jun.file.controller;
    
    import com.jun.file.service.UpLoadFileService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.PostMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.RestController;
    import org.springframework.web.multipart.MultipartFile;
    
    @RestController
    public class UpLoadFileController {
        @Autowired
        private UpLoadFileService upLoadFileService;
        @PostMapping("/upload/img")
        public String uploadImg(@RequestParam("file") MultipartFile file){
            int count=upLoadFileService.upLoadImg(file);
            return "success";
        }
    
    }
    

     

    3.服务方法

    package com.jun.file.service;
    
    import org.springframework.stereotype.Service;
    import org.springframework.web.multipart.MultipartFile;
    
    import java.io.File;
    import java.io.IOException;
    import java.util.UUID;
    
    /**
     * 这个类用于文件的上传
     */
    @Service
    public class UpLoadFileService {
        public int upLoadImg(MultipartFile file){
            String fileName = file.getOriginalFilename();
            String suffixName = fileName.substring(fileName.lastIndexOf("."));
            String name = UUID.randomUUID().toString();
            fileName = name+suffixName;
            String path = "E:/javaImg/test/";
            String path_img = path+fileName;
            File dest = new File(path_img);
            if(!dest.getParentFile().exists()){
                dest.getParentFile().mkdirs();
            }
            try {
                file.transferTo(dest);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return 0;
        }
    }
    

      

    4.测试

      

     

  • 相关阅读:
    构建之法阅读笔记06
    钢镚儿开发前会议
    构建之法阅读笔记05
    4.11第8周学习总结
    人月神话阅读笔记01
    构建之法阅读笔记04
    4.4日学习总结
    构建之法阅读笔记03
    3.28第六周学习内容总结
    二人团队项目增删改查
  • 原文地址:https://www.cnblogs.com/juncaoit/p/11188765.html
Copyright © 2011-2022 走看看