`
hulianwang2014
  • 浏览: 691499 次
文章分类
社区版块
存档分类
最新评论
  • bcworld: 排版成这样,一点看的欲望都没有了
    jfinal

jsp实现文件上传

 
阅读更多
java代码部分:
public ActionForward add(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		AddForm addForm = (AddForm) form;


		ActionErrors errors = new ActionErrors();
		try {
			// 获得要上传文件
			FormFile file = addForm.getFile();
			System.out.println(file.getContentType());
			if (!"image/pjpeg".equals(file.getContentType())) {
				errors.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage(
						"你选择的文件类型有误", false));
				this.addErrors(request, errors);
				return mapping.findForward("error");
			}
			// 获得上传文件名
			String filename = file.getFileName();


			// 获得新的文件名称
			String newfilename = DataDefine.getDateId() + "."
					+ filename.substring(filename.lastIndexOf("."));


			String imagespath = "images" + "/" + newfilename;


			// 获得服务器上传目录
			String dir = this.getServlet().getServletContext().getRealPath(
					"images");


			// 获得输入流
			InputStream in = file.getInputStream();
			// 定义文件输入流
			OutputStream fileout = new FileOutputStream(dir + File.separator
					+ newfilename);
			int c = 0;
			byte[] buffer = new byte[1024];
			while ((c = in.read(buffer, 0, 1024)) != -1) {


				fileout.write(buffer, 0, c);


			}
			file.destroy();


			// 数据库记录信息
			Product pro = new Product();
			pro.setProductname(addForm.getProductname());
			pro.setImagespath(imagespath);
			biz.saveProduct(pro);


		} catch (Exception e) {
			e.printStackTrace();
		}


		return null;
	}



jsp部分:

1.添加
<%@ page language="java" pageEncoding="utf-8"%>
<%@ taglib uri="http://jakarta.apache.org/struts/tags-bean" prefix="bean"%> 
<%@ taglib uri="http://jakarta.apache.org/struts/tags-html" prefix="html"%>
 
<html> 
	<head>
		<title>JSP for AddForm form</title>
	</head>
	<body>
		<center>
		<html:form action="/add" enctype="multipart/form-data">
		产品名称 : <html:text property="productname"/><html:errors property="productname"/><p/>
		产品的图片:<html:file property="file" /><p/>	
			<html:submit  value="添加" />
		</html:form>
		</center>
	</body>
</html>

2:显示
<table border="1" align="center">
    	<c:forEach items="${query.list}" var="product">
    	<tr>
    		<td>${product.productname}</td>
    		<td><img src="${product.imagespath}" /></td>
    	</tr>
    	</c:forEach>
    	    </table>


分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics