`
wugaokai
  • 浏览: 62059 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

Struts 1 上传图片

 
阅读更多

 

	protected String uploadImage(ActionForm form, HttpServletRequest request) {
		
		Hashtable ff = form.getMultipartRequestHandler().getFileElements();
		
		String path = "";
		Iterator<String> its = ff.keySet().iterator();
		while (its.hasNext()) {
			String key = its.next();
			FormFile formfile = (FormFile) ff.get(key);
			try {
				path = this.uploadImage(request, formfile);
				if (StringUtils.isBlank(path)) {
					continue;
				}
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return path;
	}

 

 

 

protected String uploadImage(HttpServletRequest request, FormFile file)
			throws FileNotFoundException, IOException {
		if (file == null || file.getFileSize() == 0) {
			return "";
		}
		UploadManager umanager = new UploadManagerImpl();
		String filePathInDir = umanager.upLoadFile(file,
				UploadPathUtil.getPhysicPath(request));
		file.destroy();
		return UploadPathUtil.getContextPath(request) + filePathInDir;
	}
 

 

 

 

public String upLoadFile(FormFile file, String uploadDir)
			throws FileNotFoundException, IOException {
		if (log.isDebugEnabled()) {
			log.debug("===================================");
		}
		/**
		 * 如果文件不存在 返回null
		 */
		if (file == null || file.getFileSize() <= 0) {
			if (log.isDebugEnabled()) {
				log.debug("文件不存在 返回null");
			}
			return null;
		}

		/**
		 * 判断文件类型
		 */
		// String contenttype = file.getContentType();

		// if (!StringUtils.contains(contenttype, "image")) {
		// log.error("上传文件非法类型:" + contenttype);
		// return null;
		// }

		String fileName = file.getFileName();
		int index = fileName.indexOf(".");
		String suffix = fileName.substring(index, fileName.length());

		File dirPath = new File(uploadDir);
		if (!dirPath.exists()) {
			dirPath.mkdirs();
		}
		// retrieve the file data
		InputStream stream = file.getInputStream();
		// write the file to the file specified
		num++;
		String pathInDir = System.currentTimeMillis() + "_" + num
				+ suffix.toLowerCase();

		/**
		 * if (ValidateUtil.isChineseExist(fileName)) { fileName = "1." +
		 * StringUtils.substringAfterLast(fileName, "."); } String pathInDir =
		 * System.currentTimeMillis() + "_" + fileName;
		 */

		String filePath = uploadDir + pathInDir;
		OutputStream bos = new FileOutputStream(filePath);
		int bytesRead = 0;
		byte[] buffer = new byte[8192];
		while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {
			bos.write(buffer, 0, bytesRead);
		}
		bos.close();
		stream.close();
		return pathInDir;
	}
 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics