ACTION中直接上传图片或者文档

1.  先在页面处配置上传按钮:

             form中需要添加 enctype="multipart/form-data" 参数,如下

             <html:form action="/menuSmart.shtml"  enctype="multipart/form-data" method="post">   

             以下为上传按钮,并外加显示连接

              

        <td class="dvtCellLabel">菜单图片</td>
        <td class="dvtCellInfo">
        	<html:file property="iconFile" />
        	<html:hidden property="icon"/>
        	<logic:notEmpty name="menuSmartForm" property="icon">
        		<a href="${menuSmartForm.icon}" target="_blank">查看</a>
        	</logic:notEmpty>
		</td>

2.  以下为ACTION中的上传文件操作代码:

           

	/**
	 * 文件上传
	 * @param form
	 * @param request
	 * @param isUpdate
	 * @return
	 * @throws Exception
	 */
	protected String simpleUpload(ActionForm form, HttpServletRequest request, boolean isUpdate) throws Exception {
		MenuForm menuForm = (MenuForm) form;
		String result="" ;
		FormFile file = null;
		FormFile[] files = new FormFile[]{menuForm.getIconFile(),menuForm.getBgImgFile()};
		for (int i = 0; i < files.length; i++) {
			file = files[i];
			if (file != null && !file.getFileName().equals("")) {
				String endName =  FileUtil.getFileExt(file.getFileName());
				if(!(endName.toUpperCase().equals("PNG")||endName.toUpperCase().equals("JPG")||endName.toUpperCase().equals("GIF"))){
					log.info("上传的图标文件不是图片格式");
					return null;
				}
				/*上至上传相对路径*/
				String uploadPath = ("upload" + File.separator );
				/*设置本地绝对路径*/
				String uploadDir = servlet.getServletContext().getRealPath(uploadPath);
				try {
					/*创建文件流信息*/
					File nwFile = new File(uploadDir);
					/*判断是否存在改目录文件夹*/
					if (!nwFile.exists()) 
						nwFile.mkdirs();
					long uid = System.currentTimeMillis();
					/*获取文件后缀名*/
					String fileExt = "." + endName;
					String fname = uploadDir + File.separator + uid + fileExt;
					InputStream streamIn = file.getInputStream();
					OutputStream streamOut = new FileOutputStream(fname);
					int bytesRead = 0;
					byte[] buffer = new byte[8192];
					/*开始写文件*/
					while ((bytesRead = streamIn.read(buffer, 0, 8192)) != -1) {
						streamOut.write(buffer, 0, bytesRead);
					}
					streamOut.close();
					streamIn.close();
					file.destroy();
					String realName = "upload" + "/"+ uid + fileExt;
					/*将真实的文件名设置到FORM中*/
					if(i==0){
						menuForm.setIcon(realName);
					}
					if(i==1){
						menuForm.setBgImg(realName);
					}
					result = "upload" + File.separator + uid + fileExt;
				} catch (Exception e) {
					log.error("上传图片信息是发生异常:"+e);
					return null;
				}
			}
		}
		return result;
	}

3.   如果还需要对文档进行解压缩操作,以及其他的操作,请参考 本博客中标题为 “AJAX上传下载文件”的文章。








评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值