springboot完成文件上传 15

springboot对文件上传和下载的支持是极为方便的。本节将阐述springboot中进行文件上传和下载。

1、环境约束

  • win10 64位操作系统
  • idea2018.1.5
  • maven-3.0.5
  • jdk-8u162-windows-x64

2、前提约束

3、操作步骤

  • 在主启动类同级目录下创建FileController.java:
import com.alibaba.fastjson.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

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

@Controller
public class FileController {

    final String FILE_DEST_DIR = "D:/";
    @RequestMapping(value = "/filesystem/upload", method = RequestMethod.POST)
    @ResponseBody
    public JSONObject upload(HttpServletRequest request, MultipartFile file) {
        JSONObject jsonObject = new JSONObject();
        try {
            String filePath = FILE_DEST_DIR + file.getOriginalFilename();
            file.transferTo(new File(filePath));
            jsonObject.put("success","true");
            jsonObject.put("fileId",fastdfsPath);
        }
        catch (Exception e)
        {
            e.printStackTrace();
            jsonObject.put("success","false");
        }
        return jsonObject;
    }
}
  • 在项目/src/main/resources/static文件夹下创建index.html:
<!DOCTYPE html>
<html>
<head>
    <title>file upload</title>
</head>
<body>
<form action="/filesystem/upload" method="post" enctype="multipart/form-data">
    <input type="file" name="file" />
    <input type="submit" value="upload">
</form>
</body>
</html>
  • 测试
    启动主启动类,在浏览器中输入 http://localhost:8080/index.html ,根据提示操作,就可完成文件上传。
    以上就是使用springboot完成文件上传的过程,这个demo中做了好多默认配置。
posted @ 2020-03-27 15:03  张力的程序园  阅读(224)  评论(0)    收藏  举报