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

    先建工程

    只勾选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:这里没有启动类的事,因为启动类的上层没有任何代码(官方建议启动类放在根目录)

    启动应用

    ..

     ..返回结果

     ..查看控制台

     ..找到本地文件

     ..看看可不可以访问

  • 相关阅读:
    Linux系统下/tmp目录文件重启后自动删除,不重启自动删除10天前的/TMP的文件(转)
    Docker 镜像加速器
    RabbitMQ集群和高可用配置
    k8s如何管理Pod(rc、rs、deployment)
    微信开放平台开发(1) 语义理解
    微信开放平台开发(2) 微信登录
    微信电话
    微信支付开发(1) 微信支付URL配置
    微信支付开发(2) 微信支付账号体系
    微信支付开发(3) JS API支付
  • 原文地址:https://www.cnblogs.com/LUA123/p/8460765.html
Copyright © 2011-2022 走看看