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()));//設置響應頭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();//采用零拷貝的方式實現文件的下載fileChannel.transferTo(0,fileChannel.size(),writableByteChannel);//關閉對應的資源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("文件名不可為空");}//創建流FileInputStream fis = null;FileOutputStream fos = null;//創建通道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 {//關閉資源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);}