您的位置:首页 > Web前端 > JavaScript

jsp实现图片上传功能

2011-11-21 16:48 691 查看
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;
}


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>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: