jsp实现图片上传功能

 
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>



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值