您的位置:首页 > 编程语言 > Java开发

spring boot之文件上传

2018-09-20 14:55 197 查看

文件上传的路径可以在application的配置文件中配置和获取,当文件上传到本地时,此时文件是不允许直接访问的。需要在spring boot中添加配置类(配置文件的路径是file.root.path=D:/file/)。

[code]@SuppressWarnings("deprecation")
@Configuration
public class MyWebAppConfigurer
extends WebMvcConfigurerAdapter {
@Value("${file.root.path}")
private String path;

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/upload/**").addResourceLocations("file:"+path);
super.addResourceHandlers(registry);
}

}

意思就是你将文件上传到你要上传的地方后,读取文件时,要通过路径+/upload/+文件名来读取,相当于将上传的文件和文件读取方式做了一个映射。

上传文件的类:

[code] public String checkPic(MultipartFile file,HttpServletRequest request) {
String originalFilename = file.getOriginalFilename();// 获取文件名
String extension = FilenameUtils.getExtension(originalFilename);// 获取文件的后缀
File folder = new File(path);
if (!folder.exists()) {
folder.mkdirs();
}
File f1 = new File(path + filename);
try {
FileOutputStream out = new FileOutputStream(f1);
out.write(file.getBytes());
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}

将一个路径下的文件写到另一个路径下:

[code]String path1 = path1;// 原路径
String path2 = path2;// 新路径
File folder = new File(path2);
if (!folder.exists()) {
folder.mkdirs();
}
File file = new File (path1 + name);
if(file.exists()&&file.isFile()) {
File f1 = new File(path2 + name);
byte[] b = new byte[1024];
int a;
try {
FileInputStream fis = new FileInputStream(file);
FileOutputStream out = new FileOutputStream(f1);
while ((a = fis.read(b)) != -1) {
out.write(b, 0, a);
}
fis.close();
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}

}

 

阅读更多
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: