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;
	}
 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值