java 下载文件的两种方式和java文件的上传

时间:2020-12-07 08:10:12

一:以网络的方式下载文件

try {      // path是指欲下载的文件的路径。
File file = new File(path);
// 以流的形式下载文件。
InputStream fis = new BufferedInputStream(new FileInputStream(path));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
// 清空response
response.reset();
// 设置response的Header
response.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes()));
response.addHeader("Content-Length", "" + file.length());
OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/octet-stream");
toClient.write(buffer);
toClient.flush();
toClient.close();
} catch (IOException ex) {
ex.printStackTrace();
}
return response;

二:下载本地文件

        File outFile = new File(path);
if(!outFile.exists()){
return new ReturnResponse<String>(0, "FAILURE","文件不存在");
}
OutputStream outputStream = null;
try {
response.setContentType("application/x-download");
response.addHeader("Content-Disposition", "attachment;filename="+fileName);
outputStream = response.getOutputStream(); byte[] filebytes = org.apache.commons.io.FileUtils.readFileToByteArray(outFile);
outputStream.write(filebytes);
outputStream.flush(); return new ReturnResponse<String>(0, "SUCCESS","");
} catch (IOException e) {
e.printStackTrace();
return new ReturnResponse<String>(0, "FAILURE","读取文件失败");
}finally{
if(outputStream!=null){
outputStream.close();
}
}
}

三:文件的上传

//获取文件信息和存储路径
String fileName = file.getOriginalFilename();
File outFile = new File(path);
if (!outFile.exists()) {
outFile.mkdirs();
} //保存文件
String newFileName = UUIDUtil.uuid()+fileUtils.getSuffixFromFileName(fileName);
String filepath = Paths.get(outFile.getPath(), newFileName).toString();
BufferedOutputStream stream =
new BufferedOutputStream(new FileOutputStream(new File(filepath)));
stream.write(file.getBytes());
stream.close();

四:文件的删除

File file = new File(path);
if (file.exists() && file.isFile()) {
if (file.delete()) {
return new ReturnResponse<String>(0, "删除成功!","");
} else {
return new ReturnResponse<String>(0, "删除失败!","");
}
} else {
return new ReturnResponse<String>(0, "删除失败:文件不存在!","");
}