1.文件上傳,通過通道上傳文件
/**
* 文件上傳
* @param request
* @return
*/
@PostMapping("/uploadFile")
@ResponseBody
public String uploadFiles(@RequestParam("file") MultipartFile file , HttpServletRequest request) throws IOException {
if (!file.isEmpty()) {
String saveFileName = file.getOriginalFilename();
//獲取當前路勁的地址
String systemPath =System.getProperty("user.dir")+"/imageLibrary/";
String fileName = new Date().getTime()+saveFileName;
String saveFilePath = systemPath+ fileName;
//創建文件夾
File filePath1 = new File(systemPath);
if (!filePath1.exists()) {
filePath1.mkdirs();
}
//創建文件
File filePath = new File(saveFilePath);
if (!filePath.exists()) {
filePath.createNewFile();
}
FileConfig.writeChange(saveFilePath,file);
return fileName;
} else {
return "上傳失敗,因爲文件爲空.";
}
}
public static void writeChange(String path, MultipartFile file) {
try {
File file1 = new File(path);
RandomAccessFile raf1 = new RandomAccessFile(file1, "rw");
FileChannel fw = raf1.getChannel();
ByteBuffer buffer = ByteBuffer.wrap(file.getBytes());
fw.write(buffer);
buffer.clear();
fw.close();
raf1.close();
} catch (IOException e) {
e.printStackTrace();
}
}
2.讀取文件並且顯示到瀏覽器
public static void showLogo(String path, HttpServletResponse response){
try {
OutputStream os = response.getOutputStream();
File file1 = new File(path);
RandomAccessFile raf1 = new RandomAccessFile(file1, "r");
FileChannel fw = raf1.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(500);
while (true){
buffer.clear();
int len = fw.read(buffer);
if (len == -1) {
break;
}
buffer.flip();
//也可以通過buffer寫
os.write(buffer.array());
os.flush();
}
os.close();
fw.close();
raf1.close();
} catch (IOException e) {
e.printStackTrace();
}
}