码迷,mamicode.com
首页 > 编程语言 > 详细

SpringBoot文件上传

时间:2018-02-23 10:49:16      阅读:288      评论:0      收藏:0      [点我收藏+]

标签:ram   str   pre   byte   结构   bst   real   ack   bubuko   

先建工程

技术分享图片

 

技术分享图片

 

技术分享图片

只勾选web和freemarker模板

技术分享图片

最后

技术分享图片

 

先看一下最终目录结构

技术分享图片

 

先修改pom文件,加入common-io依赖

技术分享图片

 

 然后修改Application.yml文件

spring:
  freemarker:
    templateLoaderPath: classpath:/templates/
    content-type: text/html
    charset: UTF-8
    suffix: .ftl

 

然后新建一个controller

package com.example.demo.controller;

import org.apache.commons.io.FileUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

@RestController
public class FileController {

    @RequestMapping("/index")
    public ModelAndView index(){
        ModelAndView mv = new ModelAndView("index");
        return mv;
    }

    @RequestMapping("/upload")
    public String upload(HttpServletRequest request, @RequestParam("myFile")MultipartFile file) throws IOException {
        if (file.isEmpty()) return "No File";

        String name = file.getOriginalFilename();
        System.out.println("FileName:" + name);

        String fileType = name.substring(name.lastIndexOf("."));
        System.out.println("FileType:" + fileType);

        String size = FileUtils.byteCountToDisplaySize(file.getSize());
        System.out.println("FileSize:" + size);

        String path = request.getSession().getServletContext().getRealPath("/static/img/");
        File desFile = new File(path+name);
        FileUtils.copyInputStreamToFile(file.getInputStream(), desFile);

        String info = desFile.getAbsolutePath();

        return info;
    }

}

 

最后新建一个页面

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>$Title$</title>
</head>
<body>
    <form method="post" action="/upload" enctype="multipart/form-data">
        <input type="file" name="myFile">
        <input type="submit" value="Upload">
    </form>
</body>
</html>

 

PS:这里没有启动类的事,因为启动类的上层没有任何代码(官方建议启动类放在根目录)

 

启动应用

技术分享图片

..

技术分享图片

 ..返回结果

技术分享图片

 ..查看控制台

技术分享图片

 ..找到本地文件

技术分享图片

 

 ..看看可不可以访问

技术分享图片

 

SpringBoot文件上传

标签:ram   str   pre   byte   结构   bst   real   ack   bubuko   

原文地址:https://www.cnblogs.com/LUA123/p/8460765.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!