spring boot之文件上传

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

@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/+文件名来读取,相当于将上传的文件和文件读取方式做了一个映射。

上传文件的类:

 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();
		}
	}

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

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();
		}
	
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值