上传下载

文件上传

// 上传样本
	public static void JournalFileAndExistJournalFile(UploadFile journalFile)
			throws Exception {
		// 得到存放文件路径
		File existJournalFile = new File(PathKit.getWebRootPath()
				+ "/upload/journalFile/");
		// 如果存放路径存在?上传:创建存放文件路径
		if (existJournalFile.exists()) {
			// 上传文件到指定路径
			IOUtils.copy(
					new FileInputStream(journalFile.getFile()),
					new FileOutputStream(
							new File(PathKit.getWebRootPath()
									+ "/upload/journalFile/", journalFile
									.getFileName())));
		} else {
			// 创建文件存放路径
			existJournalFile.mkdirs();
			// 上传文件到指定路径
			IOUtils.copy(
					new FileInputStream(journalFile.getFile()),
					new FileOutputStream(
							new File(PathKit.getWebRootPath()
									+ "/upload/journalFile/", journalFile
									.getFileName())));
		}
	}

ps:

UploadFile journalFile是文件对象

文件下载

@Override
	public void downloadAppendix(HttpServletResponse response, String article) {
		File file = new File(PathKit.getWebRootPath() + article);
		if(file.exists()){
			try {
				BufferedInputStream input = new BufferedInputStream(new FileInputStream(file));
				String fileName = article.substring(article.lastIndexOf("/") + 1);
				fileName = new String(fileName.getBytes("UTF-8"),"ISO8859-1");
				if(fileName.endsWith("pdf")){
					response.setContentType("application/pdf");
				}else if(fileName.endsWith("doc") || fileName.endsWith("docx")){
					response.setContentType("application/msword");
				}
				response.addHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
				response.setContentLength(Long.valueOf(file.length()).intValue());
				OutputStream out = response.getOutputStream();
				IOUtils.copy(input, out);
				out.flush();
				out.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}


你可能感兴趣的:(下载,上传)