Java文件上传下载

Java文件上传下载

相关 jar 包:

commons-beanutils.jar

commons-collections.jar

commons-fileupload-1.2.2.jar

commons-io-2.4.jar

commons-lang.jar

commons-logging.jar

dom4j-1.6.1.jar

ezmorph-1.0.6.jar

jar 包下载:http://files.cnblogs.com/files/liaolongjun/common-jar.zip

    void upload() throws Exception {
		for (FileItem item : FileUtil.getFileItems(request)) {
			ServletContext sc = request.getServletContext();
			String path = sc.getRealPath("upload"); // 上传的文件存储路劲
			String filename = item.getName();
			File file = new File(path + File.separator + filename);
			System.out.println(file);
			if (file.exists() || file.createNewFile()) {
				item.write(file); // 保存文件
			}
			// 输出 Base64 - item.get() 获取 byte[]
			System.out.println("data:" + item.getContentType() + ";base64," + new String(Base64.encodeBase64(item.get())));
		}
	}

	void download() throws Exception {
		String filepath = request.getParameter("filepath");
		File file = new File(filepath);
		response.reset();
		response.setContentType("application/x-msdownload");
		response.addHeader("Content-Disposition", "attachment; filename="" + URLEncoder.encode(file.getName(), "utf-8") + """);
		int fileLength = (int) file.length();
		response.setContentLength(fileLength);
		FileUtil.i2o(new BufferedInputStream(new FileInputStream(file)), response.getOutputStream());
	}

FileUtil.getFileItems 方法:

	/**
	 * DiskFileItemFactory 为解析器提供解析时的缺省的配置 <br>
	 * ServletFileUpload 解析 InputStream,将一个表单域(比如,一个文件输入框)中的数据封装到一个FileItem对象上<br>
	 * FileItem对象上提供了相应的方法来获取表单域中的数据
	 */
	public static List<FileItem> getFileItems(HttpServletRequest request) {
		List<FileItem> fileItems = new ArrayList<>();
		try {
			ServletFileUpload sfu = new ServletFileUpload(new DiskFileItemFactory());
			for (Object obj : sfu.parseRequest(request)) {
				FileItem item = (FileItem) obj;
				if (!item.isFormField()) { // 是否普通表单域
					fileItems.add(item);
				}
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return fileItems;
	}

  

FileUtil.i2o 方法:

	public static void i2o(InputStream is, OutputStream os) {
		try {
			byte[] b = new byte[1024 * 1024]; // 一次读取1M
			int n = 0;
			while ((n = is.read(b)) != -1)
				os.write(b, 0, n);// 这个n还不能去了
			is.close();
			os.flush();
			os.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

  

原文地址:https://www.cnblogs.com/liaolongjun/p/6718253.html