Java文件上傳下載

Java文件上傳下載

 

相關 jar 包:java

commons-beanutils.jarapp

commons-collections.jardom

commons-fileupload-1.2.2.jarcode

commons-io-2.4.jarorm

commons-lang.jar對象

commons-logging.jarblog

dom4j-1.6.1.jarip

ezmorph-1.0.6.jarutf-8

 

jar 包下載:http://files.cnblogs.com/files/liaolongjun/common-jar.zipget

 

    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();
		}
	}
相關文章
相關標籤/搜索