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.测试

      

     

  • 相关阅读:
    Orderly Class
    POJ2513 【并查集+欧拉路径+trie树】
    POJ2195 Going Home【KM最小匹配】
    洛谷P2604 最大流+最小费用最大流
    小数转分数
    威尔逊定理
    luogu P6564 [POI2007] 堆积木KLO 树状数组+dp
    Codeforces Round #644 (Div. 3) H——Binary Median 二分
    luogu P4933 大师 线性dp
    Codeforces Round #643 (Div. 2) D——Game With Array
  • 原文地址:https://www.cnblogs.com/juncaoit/p/11188765.html
Copyright © 2011-2022 走看看