• SpringBoot之文件上传


     1 package org.springboot.controller;
     2 
     3 import org.apache.logging.log4j.LogManager;
     4 import org.apache.logging.log4j.Logger;
     5 import org.springboot.constant.Constant;
     6 import org.springframework.stereotype.Controller;
     7 import org.springframework.web.bind.annotation.*;
     8 import org.springframework.web.multipart.MultipartFile;
     9 
    10 import java.io.File;
    11 import java.io.IOException;
    12 
    13 /**
    14  * @Auther:GongXingRui
    15  * @Date:2018/12/25
    16  * @Description: 文件下载
    17  **/
    18 @Controller
    19 public class FileUpload {
    20     Logger logger = LogManager.getLogger(FileUpload.class);
    21 
    22     @GetMapping("/upload")
    23     public String upload() {
    24         return "upload";
    25     }
    26 
    27     @PostMapping("/upload")
    28     @ResponseBody
    29     public String upload(@RequestParam("file") MultipartFile file) {
    30         if (file.isEmpty()) {
    31             return "上传失败,请选择文件";
    32         }
    33 
    34         String fileName = file.getOriginalFilename();
    35 //        String filePath = "C:/Temp/upload";
    36         String filePath = Constant.CONFIG_PROPERTIES.getProperty("upload.path");
    37         File dest = new File(filePath + File.separator + fileName);
    38         //判断文件是否已经存在
    39         if (dest.exists()) {
    40             logger.info("文件已经存在 -> " + dest.getPath());
    41         }
    42         if (!dest.getParentFile().exists()) {
    43             dest.getParentFile().mkdirs();
    44             logger.info("目录不存在,自动创建 -> " + dest.getParentFile().getPath());
    45         }
    46         try {
    47             file.transferTo(dest);
    48             logger.info("上传成功");
    49             return "上传成功";
    50         } catch (IOException e) {
    51             logger.error(e.toString(), e);
    52         }
    53         return "上传失败!";
    54     }
    55 }
  • 相关阅读:
    美团霸面---我想说说心里话。
    docker在ubuntu14.04下的安装笔记
    ubuntu14.04 upgrade出现【Ubuntu is running in low-graphics mode】问题的一个解决办法
    Python2和Python3在windows下共存
    Python发送邮件
    Python在安装第三方模块遇到的问题及解决办法
    127.0.0.1和localhost完全相等吗?
    vim总结
    linux shell学习笔记
    Jenkins +JUnit
  • 原文地址:https://www.cnblogs.com/gongxr/p/10189244.html
Copyright © 2020-2023  润新知