Spring Boot 文件上传

 

<form method="post" enctype="multipart/form-data" action="/file/upload">
    文件:<input type="file" name="myFile"><br>
    <input type="submit" value="上传">
</form>
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

@Controller
@RequestMapping("/file")
public class FileController {

    private final Logger logger = LoggerFactory.getLogger(FileController.class);

    @ResponseBody
    @PostMapping("/upload")
    public String upload(@RequestParam("myFile") MultipartFile file) {
        if (file.isEmpty()) {
            return "文件为空";
        }
        String fileName = file.getOriginalFilename();//获取文件名
        logger.info("上传的文件名为:" + fileName);
        String suffixName = fileName.substring(fileName.lastIndexOf("."));//获取文件的后缀名
        logger.info("上传文件的后缀名为:" + suffixName);
        String filePath = "d:/temp/";
        File dest = new File(filePath + fileName);
        if (!dest.getParentFile().exists()) {//检测是否存在目录
            dest.getParentFile().mkdir();
        }
        try {
            file.transferTo(dest);
            return "上传成功";
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "上传失败";
    }

}

在 application.properties 中进行如下配置

#默认支持文件上传
spring.http.multipart.enabled=true
#支持文件写入磁盘
spring.http.multipart.file-size-threshold=0
#上传文件的临时目录
spring.http.multipart.location=
#最大支持文件大小
spring.http.multipart.max-file-size=1MB
#最大支持请求大小
spring.http.multipart.max-request-size=10MB

 

posted on 2017-09-22 00:05  whlshot  阅读(314)  评论(0编辑  收藏  举报

导航