1.文件下載
/**NIO文件下載工具類
* @author olalu
*/
public class NioDownloadUtils {
/**
* @description:
* @param file: 要下在文件
* @return: void
*/
public static void downloadDoc(File file,HttpServletResponse response) throws IOException {
OutputStream outputStream = response.getOutputStream();
String contentType = Files.probeContentType(Paths.get(file.getAbsolutePath()));
//設(shè)置響應(yīng)頭
response.setHeader("Content-Type", contentType);
response.setHeader("Content-Disposition", "attachment;filename="+ new String(file.getName().getBytes("utf-8"),"ISO8859-1"));
response.setContentLength((int) file.length());
//獲取文件輸入流
FileInputStream fileInputStream = new FileInputStream(file);
//獲取輸出流通道
WritableByteChannel writableByteChannel = Channels.newChannel(outputStream);
FileChannel fileChannel = fileInputStream.getChannel();
//采用零拷貝的方式實現(xiàn)文件的下載
fileChannel.transferTo(0,fileChannel.size(),writableByteChannel);
//關(guān)閉對應(yīng)的資源
fileChannel.close();
outputStream.flush();
writableByteChannel.close();
}
public static void downloadDoc(String path,HttpServletResponse response) throws IOException {
File file = new File(path);
if (!file.exists()){
throw new RuntimeException("文件不存在");
}
downloadDoc(file,response);
}
}
2.文件上傳
/**
* 文件上傳方法
*/
public static Result uploading(MultipartFile file) {
//獲取文件名
String realName = file.getOriginalFilename();
String newName = null;
if(realName != null && realName != ""){
//獲取文件后綴
String suffixName = realName.substring(realName.lastIndexOf("."));
//生成新名字
newName = UUID.randomUUID().toString().replaceAll("-", "")+suffixName;
}else {
return Result.fail("文件名不可為空");
}
//創(chuàng)建流
FileInputStream fis = null;
FileOutputStream fos = null;
//創(chuàng)建通道
FileChannel inChannel = null;
FileChannel outChannel = null;
try {
fis = (FileInputStream)file.getInputStream();
//開始上傳
fos = new FileOutputStream(UPLOAD_URL+"\\"+newName);
//通道間傳輸
inChannel = fis.getChannel();
outChannel = fos.getChannel();
//上傳
inChannel.transferTo(0,inChannel.size(),outChannel);
}catch (IOException e){
return Result.fail("文件上傳路徑錯誤");
}finally {
//關(guān)閉資源
try {
if (fis != null) {
fis.close();
}
if (fos != null) {
fos.close();
}
if (inChannel != null) {
inChannel.close();
}
if (outChannel != null) {
outChannel.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return Result.ok(newName);
}
文章來源地址http://www.zghlxwxcb.cn/news/detail-648704.html
文章來源:http://www.zghlxwxcb.cn/news/detail-648704.html
到了這里,關(guān)于使用nio代替?zhèn)鹘y(tǒng)流實現(xiàn)文件上傳和下載功能的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!