1. 程式人生 > >spring boot之檔案上傳

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