其他分享
首页 > 其他分享> > SpringBoot中的文件上传

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";
    }
}

 

标签:文件,fileupload,SpringBoot,springframework,io,import,org,上传,String
来源: https://www.cnblogs.com/spring8889/p/15775651.html