图片上传及实时显示--struts2、jsp、java
图片上传需要action的enctype="multipart/form-data"。大致的原理就是,在上传页面写两个form表单,一个用来显示出来给用户看,一个隐藏起来上传图片。然后图片上传后再显示在页面里。
1、jsp页面
< script type="text/javascript">
function upload(){
var of = $("#imgFile");
//检查是否选择了图片
if(of.val()=="") {
;
return;
} //将file移动至上传表单
$("#fileContent").empty();
$("#fileContent").append(of.clone()); $("#uploadForm").submit(); }
< /script>
id="uploadForm" action="imgUploadAction.action" method="post"
enctype="multipart/form-data" target="hiddenIframe"
style="display:none;width:0px;height:0px;">
< span id="fileContent"><
/span>
< /form>
< iframe name="hiddenIframe" frameborder="0"
style="display:none;width:0px;height:0px;"><
/iframe>
< form
action="saveUser.action" method="post">
姓名: < input type="text" name="user.username"
size="20">< br>
password: < input type="password"
name="user.password" size="20">< br>
age: < input type="text" name="user.age"
size="20">< br>< br>
< span id="ufc">< input type="file"
name="file" id="imgFile" /> < input type="button" value="上传"
οnclick="upload()">< br>
< img alt="" src="" name="img"
id="img">
< br>< input type="text" id="imgFiles"
/> <
/form> < /body>
**************具体实现上传图片的action是上面那个隐藏的form,注意form的target和下面一个隐藏的iframe。*******
2、strut.xml
< action
name="imgUploadAction" class="com.test.commenAction"
method="upload">
<
result>/iframe_upload.jsp< /result>
< /action>
**********返回到的一个jsp页面,这个页面我们一会再说***********
3、commenAction.java
private File file;
private String fileFileName;
private String res;
get和set方法..........
public String upload() throws Exception
{
ActionContext ac =
ActionContext.getContext(); ServletContext sc =
(ServletContext)
ac.get(ServletActionContext.SERVLET_CONTEXT); String path =
sc.getRealPath("/img"); InputStream is = new
FileInputStream(file);
OutputStream os = new
FileOutputStream(path+"/"+ fileFileName);
byte[] buffer = new
byte[1024];
int length = 0;
while (-1 != (length =
is.read(buffer)))
{
os.write(buffer,0,length);
}
os.close();
return "success";
}
********处理后res把图片上传后的地址返回到页面*********
4、iframe_upload.jsp 在strut.xml里配置的。
< script src="/jquery.js"
type="text/javascript">< /script>
< script type="text/javascript">
parent.document.getElementByIdx_x_x_x("img").src="${res}";
< /script>
********这个页面就是显示在第一个jsp页面里面那个iframe中*******
上传图片及实时显示的功能就完成了。