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[1024];
			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");
	}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值