Springboot 文件上传

Posted w53064

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Springboot 文件上传相关的知识,希望对你有一定的参考价值。

单文件上传

public String SingleUpload(MultipartFile file, String url) {
String fix;
String fileName;
File tempFile;
if
(!file.isEmpty()) {
fix = getFix(file.getOriginalFilename());
fileName = new Date().getTime() + fix;
tempFile = new File(url + "/" + fileName);
if
(!tempFile.getParentFile().exists()) {
tempFile.getParentFile().mkdirs();
}
try {
BufferedOutputStream outputStream = new BufferedOutputStream(new FileOutputStream(tempFile));
outputStream.write(file.getBytes());
outputStream.flush();
outputStream.close();
} catch (FileNotFoundException e) {
return "上传失败," + e.getMessage();
} catch (IOException e) {
return "上传失败," + e.getMessage();
}
return "上传成功";
} else {

return "上传失败,因为文件是空的.";
}

 

多文件上传

public String MultipartUpload(String url,MultipartHttpServletRequest multiRequest) {
List<MultipartFile> multipartFiles = multiRequest.getFiles("files");
MultipartFile multipartFile = null;
String fileName,fix;
File tempFile;
BufferedOutputStream bufferedOutputStream = null;
for
(int i = 0; i < multipartFiles.size(); ++i) {
multipartFile = multipartFiles.get(i);
if
(!multipartFile.isEmpty()) {
fix=getFix(multipartFile.getOriginalFilename());
fileName=new Date().getTime()+fix;
String path = url+"/"+fileName;
tempFile=new File(path);
if
(!tempFile.getParentFile().exists()) {
tempFile.getParentFile().mkdirs();
}
try {
bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(tempFile));
byte
[] bytes = multipartFile.getBytes();

bufferedOutputStream.write(bytes, 0, bytes.length);
} catch (FileNotFoundException e) {

// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {

// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {

e.printStackTrace();
}

} else {
System.out.println("上传的文件为空");
}
System.out.println("上传文件完成了");

}
return "request ok";

 

获取文件后缀名函数

//获取后缀名
public static String getFix(String str) {

int index = 0;
for
(int i = 0; i < str.length(); i++) {

if (str.charAt(i) == ‘.‘) {
index = i;
}
}

return str.substring(index);
}








































































以上是关于Springboot 文件上传的主要内容,如果未能解决你的问题,请参考以下文章

springboot调整上传文件大小限制

SpringBoot文件上传

springboot怎么获得文件上传的地址

springboot上传文件写入数据库

springboot自带容器的上传文件怎么访问

springboot文件上传: 单个文件上传 和 多个文件上传