JAVA上传下载

原创
2019/07/24 10:42
阅读数 13
  public class FileUtil {
	/**
	*
	* Description: 复制文件
	*
	 * [@param](https://my.oschina.net/u/2303379) srcFile 上传文件
	 * [@param](https://my.oschina.net/u/2303379) filePath 保存文件地址
	* [@return](https://my.oschina.net/u/556800)
	* [@date](https://my.oschina.net/u/2504391) 2019/1/18
	*/
   public static void copyFile(MultipartFile srcFile, String filePath) throws Exception {
	  // 判断是否上传文件
	  if (srcFile == null || srcFile.isEmpty() || StringUtils.isBlank(filePath)) {
		 throw new NullPointerException("上传文件为空");
	  }
	  InputStream inputStream = srcFile.getInputStream();
	  File file = new File(filePath);
	  if (!file.exists()) {
		 file.getParentFile().mkdirs();
	  }
	  FileOutputStream outputStream = new FileOutputStream(file);
	  try {
		 IOUtils.copy(inputStream, outputStream);
	  } finally {
		 IOUtils.closeQuietly(inputStream);
		 IOUtils.closeQuietly(outputStream);
	  }
   }
}




/**
 * Description: 从本地下载PDF
 *
 * [@param](https://my.oschina.net/u/2303379) fileName
 *            文件名
 * @return
 * @date 2018年02月01日
 */
public static boolean copyPdf(HttpServletRequest request, HttpServletResponse response, String filePath,
		String fileName) {
   File file = new File(filePath + fileName);
   // 文件不存在,直接返回
   if (!file.exists()) {
	  return false;
   }
   BufferedInputStream inputStream = null;
   BufferedOutputStream outputStream = null;
   try {
	  setDownLoadResponseHeader(request, response, fileName);
	  inputStream = new BufferedInputStream(new FileInputStream(file));
	  outputStream = new BufferedOutputStream(response.getOutputStream());
	  IOUtils.copy(inputStream, outputStream);
   } catch (IOException e) {
	  e.printStackTrace();
   } finally {
	  try {
		 if (inputStream != null) {
			inputStream.close();
		 }
		 if (outputStream != null) {
			outputStream.close();
		 }
	  } catch (IOException e) {
		 e.printStackTrace();
	  }
   }
   return true;
}
展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
OSCHINA
登录后可查看更多优质内容
返回顶部
顶部