码迷,mamicode.com
首页 > 编程语言 > 详细

Springboot 文件上传

时间:2018-05-21 14:39:50      阅读:182      评论:0      收藏:0      [点我收藏+]

标签:byte   rate   nts   parent   system   put   buffer   multipart   文件   

单文件上传

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 文件上传

标签:byte   rate   nts   parent   system   put   buffer   multipart   文件   

原文地址:https://www.cnblogs.com/w53064/p/9066388.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!