文件下载
@Override
public void downloadAuthorization(Long id, HttpServletResponse response) {
DeviceAuthorization authorization = getById(id);
InputStream fis = null;
try {
fis = new BufferedInputStream(new FileInputStream(authorization.getFilePath()));
}catch (FileNotFoundException notFoundException){
notFoundException.printStackTrace();
throw new BusinessException("系统找不到指定的路径:" + authorization.getFilePath());
}
try {
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
response.reset();
response.addHeader("Content-Disposition", "attachment;filename=" + new String(authorization.getFileName().getBytes()));
response.addHeader("Content-Length", "" + buffer.length);
OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/octet-stream");
toClient.write(buffer);
toClient.flush();
toClient.close();
} catch (IOException e) {
e.printStackTrace();
throw new BusinessException("下载文件失败");
}
}
文件上传
@Override
public void upload(MultipartFile file) {
String filename = file.getOriginalFilename();
String path = System.getProperty("user.dir") + File.separator + "file" + File.separator + filename;
File file1 = new File(path);
if (!file1.exists()) {
FileOutputStream fop = null;
try {
fop = new FileOutputStream(file1);
file1.createNewFile();
byte[] contentInBytes = new byte[0];
contentInBytes = file.getBytes();
fop.write(contentInBytes);
fop.flush();
fop.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}