1、最近在使用spring boot框架做一个项目,这里面包含着众多的上传于下载工作,在这里我做了一些总结和归纳。
2、spring boot项目的默认Tomcat规定上传文件的最大值不得超过1M,如果超过了 ,在spring boot的控制台就会抛错,所以咱们需要首先在spring boot项目的配置文件application.properties文件中添加配置。
#配置文件上传的限制
spring.servlet.multipart.enabled=true
#单个文件大小限制
spring.servlet.multipart.max-file-size=10MB
#设置总上传数据大小
spring.servlet.multipart.max-request-size=1000MB
3、文件上传这边使用的是传统form表单进行上传。后台进行接收上传的数据。
@Override
public int addFile(File2 ffile, HttpServletRequest request, MultipartFile fileField) throws Exception {
String fileName = fileField.getOriginalFilename();
String fileUrl=null;
BufferedOutputStream bos = null;
try {
File path=new File(ResourceUtils.getURL("classpath:").getPath());
if(!path.exists()) path = new File("");
//构建真实的文件路径
File newFile = new File(path.getAbsolutePath(),"static/assets/file/");
if(!newFile.exists()) newFile.mkdirs();
//转存文件到指定路径,如果文件名重复的话,将会覆盖掉之前的文件,这里是把文件上传到 “绝对路径”
// Check for Unix-style path
int unixSep = fileName.lastIndexOf('/');
// Check for Windows-style path
int winSep = fileName.lastIndexOf('\\');
// Cut off at latest possible point
int pos = (winSep > unixSep ? winSep : unixSep);
if (pos != -1) {
// Any sort of path separator found...
fileName = fileName.substring(pos + 1);
}
String backgroundPicUrl = newFile.getAbsolutePath()+ "\\" + ffile.getFileName()
+ fileName.substring(fileName.lastIndexOf('.'));
byte[] bytes = fileField.getBytes();
bos = new BufferedOutputStream(new FileOutputStream(new File(backgroundPicUrl)));
bos.write(bytes);
fileUrl=request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()+"/assets/file/" +ffile.getFileName() + fileName.substring(fileName.lastIndexOf('.'));
} catch (Exception e) {
e.printStackTrace();
}
logger.info( user.getUserName()+"用户添加了名字为"+ffile.getFileName()+"的文件" );
}
但上传的时候有些浏览器上传的时候:String fileName = fileField.getOriginalFilename();获取到的值不同,谷歌浏览器是获取的文件名,而ie浏览器,edge浏览器中fileName获取到时候是上传文件的地址,所以为了解决这一问题,可以直接取出上传文件的类型,然后重新定义一下文件名进行保存。
int unixSep = fileName.lastIndexOf('/');
// Check for Windows-style path
int winSep = fileName.lastIndexOf('\\');
// Cut off at latest possible point
int pos = (winSep > unixSep ? winSep : unixSep);
if (pos != -1) {
// Any sort of path separator found...
fileName = fileName.substring(pos + 1);
}
最终将上传文件的路径url保存在数据库中。
4、这边有一个上传文件存储位置的问题,一些客户要求存储位置不能为服务器的绝对路径,出现C盘,D盘等问题,所以在这开发者基本都会将文件保存在本项目下的相对路径中。在spring boot项目中在本地的时候 文件会保存在target文件下面,在服务器中就会存储在相对路径下面。
File path=new File(ResourceUtils.getURL("classpath:").getPath());
//构建真实的文件路径
File newFile = new File(path.getAbsolutePath(),"static/assets/file/");