程序员一代码搬运工
【Java学习心得和Java学习技术个人总结】

java 上传文件和下载文件 工具类

public static void downloadFile(String fileName, String downloadName, HttpServletResponse response){
		try {
			response.setContentType("octets/stream");
			response.addHeader("Content-Type", "text/html; charset=utf-8");
			String downLoadName = new String(downloadName.getBytes("gbk"), "iso8859-1");
			response.addHeader("Content-Disposition", "attachment;filename=" + downLoadName);
		
			FileInputStream fileInputStream = new FileInputStream(fileName);
			OutputStream out = response.getOutputStream();
			int i = 0;
			while ((i = fileInputStream.read()) != -1) {
				out.write(i);
			}
			fileInputStream.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 上传文件
	 * 
	 * @param file
	 *            文件
	 * @param radomfileName
	 *            保存文件名
	 * @param materialFilePath
	 *            保存路径
	 * @return
	 */
	public static boolean fileUpload(MultipartFile file, String radomfileName,
			String materialFilePath) {
		boolean flag = true;
		File baseFile = new File(materialFilePath);
		File trainFile = new File(baseFile, radomfileName);
		if (!baseFile.exists()) {
			baseFile.mkdirs();
		}
		try {
			file.transferTo(trainFile);
		} catch (IllegalStateException e) {
			flag = false;
		} catch (IOException e) {
			flag = false;
		}// 保存文件
		return flag;
	}

 

赞(0)
未经允许不得转载:程序员一代码搬运工 » java 上传文件和下载文件 工具类
分享到: 更多 (0)