赞
踩
大家使用spring-mvc来实现文件上传已经很简单了,其实spring这个团队非常的伟大,为什么这么说呢,使用spring-boot来实现文件上传功能更加的方便快捷,
废话不多上直接上代码
首先需要创建spring-boot项目这点都不用说,不会创建的建议搭建可以先学一下怎么来创建springboot项目。
由于只是实现一个简单的上传功能,所以在这里我就不在使用模板引擎了,直接在static静态文件中创建一个upload.html文件,访问静态文件来操作。
代码如下
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <title>单文件上传</title>
- </head>
- <body>
- <form action="/upload" method="post" enctype="multipart/form-data">
- <input type="file" name="uploadFile" value="请选择文件">
- <input type="submit" value="上传">
- </form>
- </body>
- </html>
重要的事情说三遍,在“form”表单中一定要加上“enctype="multipart/form-data"这句话。否则你后端代码是获取不到上传的文件的,关于为什么这样做,不知道的朋友们可以学习一下HTML的知识
接下来呢需要创建一个文件上传的控制类,用来处理上传的文件:
- package com.fyn.springboot.upload.controller;
-
- import org.springframework.web.bind.annotation.PostMapping;
- 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;
- import java.text.SimpleDateFormat;
- import java.util.Date;
- import java.util.UUID;
-
- @RestController
- public class FileUpload {
-
- SimpleDateFormat sd = new SimpleDateFormat("yyyy/MM/dd");
- @PostMapping("/upload")
- public String upload(MultipartFile uploadFile, HttpServletRequest req){
- String realPath = req.getSession().getServletContext().getRealPath("/uploadFile");
- String format = sd.format(new Date());
- File file = new File(realPath + format);
- if (!file.isDirectory()){
- file.mkdirs();
- }
- String oldName = uploadFile.getOriginalFilename();
- String newName = UUID.randomUUID().toString() + oldName.substring(oldName.indexOf("."), oldName.length());
- try {
- uploadFile.transferTo(new File(file,newName));
- String path = req.getScheme() + "://" + req.getServerName() + ":" + req.getServerPort() + "/uploadFile/" + format + newName;
- return path;
- } catch (IOException e) {
- e.printStackTrace();
- }
- return "上传失败";
- }
- }

接下来访问127.0.0.1:8080/upload.html就会出现之前写的文件上传页面!
点击选择文件上传,后会返回对应的文件存储路径地址
此时可以复制路径,浏览器访问,查看上传结果!
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。