java struts2 上传图片,图片上传及实时显示--struts2、jsp、java

图片上传及实时显示--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中*******

上传图片及实时显示的功能就完成了。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值