javazhou 发表于 2013-1-15 02:59:27

struts文件上传

jsp页面代码:
<html><head><title>添加产品</title></head><html:errors property="error.add"/><html:errors property="error.type" /><html:errors property="error.size" /><body><html:form action="/addProduct.do?method=addProduct" method="post"enctype="multipart/form-data" >产品图片:<html:file property="file"></html:file><html:submit value="添加" /></html:form></body></html> 
详细代码1:
public ActionForward addProduct(ActionMapping mapping, ActionForm form,HttpServletRequest request, HttpServletResponse response) {ProductForm productForm = (ProductForm) form;Product product = productForm.getProduct();FormFile file = productForm.getFile();ActionErrors errors = new ActionErrors();try {// 设置只能上传图片类型的文件if (!file.getContentType().equals("image/pjpeg")) {errors.add("error.type",new ActionMessage("你选择的文件类型错误!", false));this.addErrors(request, errors);return new ActionForward(mapping.getInput());}// 设置上传文件的大小int maxFileSize = 3 * 1024 * 1024;if (file.getFileSize() > maxFileSize) {errors.add("error.size", new ActionMessage("你选择的文件过大!", false));this.addErrors(request, errors);return new ActionForward(mapping.getInput());}// 获得服务器存放上传文件的绝对路径String dir = this.getServlet().getServletContext().getRealPath("images");// 获得上传的文件名String fileName = file.getFileName();// 用当前时间作为上传的新文件名String newFileName = DataDefine.getDateId()+ fileName.substring(fileName.lastIndexOf("."));// 存储到数据中图片的路径String imagePath = "images" + "/" + newFileName; 
 详细代码2:
                                             // 获得文件输入流InputStream is = file.getInputStream();// 创建文件输出流OutputStream os = new FileOutputStream(dir + File.separator+ newFileName);byte[] buffer = new byte;int b = 0;while ((b = is.read(buffer, 0, 1024)) != -1) {os.write(buffer, 0, b);}// 添加至数据库product.setImagePath(imagePath);boolean isFlag = productBiz.addProduct(product);if (!isFlag) {errors.add("error.add", new ActionMessage("添加产品失败!", false));this.addErrors(request, errors);return new ActionForward(mapping.getInput());}request.setAttribute("message", "添加产品成功");} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();} finally {file.destroy();}return mapping.findForward("success");} 
 
页: [1]
查看完整版本: struts文件上传