SpringBoot中的文件上传

1、引入jar包依赖

        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.1</version>
        </dependency>

        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>

2、fileupload.html

<!DOCTYPE html>
<html lang="zh" xmlns:th="http://www.thymeleaf.org/">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
  <form th:action="@{/upload}" method="post" enctype="multipart/form-data">
      <input type="file" name="fileTest"/>
      <input type="submit" value="上传"/>
  </form>
</body>
</html>

3、FileDealer.java

package com.csp.springbootjwt.Controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;

@Controller
public class FileDealer {

    @RequestMapping("/upload")
    @ResponseBody
    public String upload(MultipartFile fileTest, HttpServletRequest request) throws IOException {
        //获取文件的原始名
        String filename = fileTest.getOriginalFilename();
        System.out.println(filename);
        //根据相对路径获取绝对路径
        String realPath = request.getSession().getServletContext().getRealPath("/");

        fileTest.transferTo(new File(realPath,filename));

        return "success";
    }

    @RequestMapping("/file")
    public String tofile(){
        return "/fileupload";
    }
}

 

上一篇:The type initializer for 'Gdip' threw an exception


下一篇:与文件上传有关的commons-fileupload和commons-io的jar包的下载