版权声明:ApassionBoy https://blog.csdn.net/weixin_43150581/article/details/84174614
最近一直在忙事情,有段时间没有发教程了,在这里说声抱歉,
不过关于springboot的jaio教程我还是会更新完整的,那就开始今天的内容
今天要讲的是文件的上传用法,直接来例子讲解:
1、首先去写一个简单的页面file.html,可以触发就行,代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<!-- 单个文件上传 -->
<form action="/upload" method="POST" enctype="multipart/form-data">
文件:<input type="file" name="test" /> <input type="submit" />
</form>
<!--将查询到的数据添加到xls文件中,并下载 -->
<a href="/UserExcelDownloads">下载test</a>
<p>多文件上传</p>
<form method="POST" enctype="multipart/form-data"
action="/batch/upload">
<p>
文件1:<input type="file" name="file" />
</p>
<p>
文件2:<input type="file" name="file" />
</p>
<p>
<input type="submit" value="上传" />
</p>
</form>
</body>
</html>
2、创建一个FileController.java,此类中写的是文件上传的业务代码
package com.test.controller;
import java.io.File;
import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
@Controller
public class FileController2 {
private static final Logger logger = LoggerFactory.getLogger(FileController2.class);
// 文件上传相关代码
@RequestMapping(value = "upload")
@ResponseBody
public String upload(@RequestParam("test") MultipartFile file) {
if (file.isEmpty()) {
return "文件为空";
}
// 获取文件名
String fileName = file.getOriginalFilename();
logger.info("上传的文件名为:" + fileName);
// 获取文件的后缀名
String suffixName = fileName.substring(fileName.lastIndexOf("."));
logger.info("上传的后缀名为:" + suffixName);
// 文件上传后的路径
String filePath = "E://test//";
// 解决中文问题,liunx下中文路径,图片显示问题
// fileName = UUID.randomUUID() + suffixName;
File dest = new File(filePath + fileName);
// 检测是否存在目录
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();
}
try {
file.transferTo(dest);
return "上传成功";
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return "上传失败";
}
}
3、上面两步骤wan'完成以后,然后你就直接去访问file.html页面,
然后直接点击上传ti'j提交就可以看到到效果了
4、如果使用本人自己的项目,访问地址如下:
http://localhost:8090/login UserName:admin UserPassword:12345
GitHub源码地址:https://github.com/APassionMy/github.springboot-two