当前位置 : 主页 > 编程语言 > c++ >

文件下载(文件重命名)

来源:互联网 收集:自由互联 发布时间:2021-07-03
文件下载(文件重命名) @Overridepublic void downloadFile(Long id, HttpServletResponse response) {SysFileLib sysFileLib = findOne(id);if(sysFileLib==null){logger.error("对象不存在,fileLibId:" + id);String message = ServiceM
文件下载(文件重命名)
@Override
	public void downloadFile(Long id, HttpServletResponse response) {
		SysFileLib sysFileLib = findOne(id);
		if(sysFileLib==null){
			logger.error("对象不存在,fileLibId:" + id);
			String message = ServiceManager.sysExceptionCodeService.getMessageByCode(ResGlobalExt.COMMON_OBJECT_NO_FOUND);
			throw new BusinessException(ResGlobalExt.COMMON_OBJECT_NO_FOUND, message);
		}

		File file = FileSystemEngine.getFileSystem().getLocalFile(sysFileLib.getSysFileId());
		if(!file.exists()){
			logger.error("文件不存在,fileNm:" + sysFileLib.getFileNm());
			String message = ServiceManager.sysExceptionCodeService.getMessageByCode(ResGlobalExt.COMMON_OBJECT_NO_FOUND);
			throw new BusinessException(ResGlobalExt.COMMON_OBJECT_NO_FOUND, message);
		}

		FileInputStream fis = null;
		OutputStream os = null;
		try {
			fis = new FileInputStream(file);
			String sysFileId = sysFileLib.getSysFileId();
			String exName = sysFileId.substring(sysFileId.lastIndexOf("."));
			String filename = new String((sysFileLib.getFileNm() + exName).getBytes("GBK"), "ISO-8859-1");
			response.setContentType("application/octet-stream");
			response.addHeader("Content-Disposition", "attachment;filename=" + filename);
			response.addHeader("Content-Length", "" + file.length());

			os = response.getOutputStream();
			byte[] buffer = new byte[1024];
			int temp = 0;
			while ((temp = fis.read(buffer))!=-1){
				os.write(buffer, 0, temp);
			}
			os.flush();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(fis!=null){
				try {
					fis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

			if(os!=null){
				try {
					os.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
网友评论