图片上传错误提示的部分源码:
Error setting expression 'image' with value '[Ljava.lang.String;@c78e02'
ognl.MethodFailedException: Method "setImage" failed for object com.graduateInfo.action.attachment.AttachmentAction@4577f9 [java.lang.NoSuchMethodException: com.graduateInfo.action.attachment.AttachmentAction.setImage([Ljava.lang.String;)]。
异常提示:[Struts2框架无法从我的setImage()方法中获得image这个值]
...
/-- Encapsulated exception ------------\
再仔细看JSP页面:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib prefix="s" uri="/struts-tags"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'personal_image_upload.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<link rel="stylesheet" type="text/css"
href="<%=basePath%>css/table/tableCss.css">
<script type="text/javascript"
src="<%=basePath%>js/jquery/jquery-1.7.2.min.js"></script>
</head>
<script type="text/javascript">
function uploadImage(){
var filePath=$("#image").val();
var reg=/\.gif|jpg|jpeg|png|bmp$/;
if(filePath==''){
alert('上传的图片不能为空!');
}else if(!reg.test(filePath)){
alert('请导入正确的图片!');
}else{
$('#ff').submit();
}
}
</script>
<body>
<form id="ff" action="attachment/attachmentAction!saveUserImage.action"
enctype="multipart/form-data">
<br />
<br />
上传图片:
<s:file name="image" id="image"></s:file>
<input type="button" value="上传" onclick="uploadImage();" />
</form>
<div style="background: #FAFBDD; padding: 3px;" id="uploadImageMsg" align="center">
<font color="red">${sessionScope.uploadImageMsg}</font>
</div>
</body>
</html>
控制层部分源码:
public class AttachmentAction extends ActionSupport {
/**
* 导入的图片
*/
private File image;
/**
* 导入的图片名称
*/
private String imageFileName;
/**
* 导入的图片类型
*/
private String imageContentType;
//......
}
纠错结果:
造成这个错误的原因有1)第一个错误是要实现文件上传的jsp里面的form元素的ectype没有设置成:enctype="multipart/form-data" ;2)第二个错误也是很多人没有注意的,就是我们的form提交方法应该是method="post"。而且关键还是这个method,纠正后的表单设置为:<form id="ff" method="post" action="attachment/attachmentAction!saveUserImage.action"
enctype="multipart/form-data">
。
分析:
enctype="multipart/form-data" 表示文件提交的内容是二进制的,可以很好的处理照片。而且get方法是要附加在link后面去提交的,因而提交的都是String。所以应该选择使用post(头传输)。但是也应该注意,使用post传输,更安全更高效。