您的位置:首页 > Web前端 > JQuery

SSH+jquery+ajax实现上传图片并回显

2014-03-02 00:46 1091 查看
从昨天到今天弄了好久,网上找的还是不是很全面。有些代码看的不清不楚的。有点费解。

担心自己后面也忘记了,特此记录。

先贴代码,

jsp中:要先导入jquery.js和Ajaxupload.js两个js文件

$(document).ready(function (){
var button = $('#button1');
new AjaxUpload(button,{
action:'<%=request.getContextPath()%>/user/uploadphoto!loadImg.action',
name:'myfile',//这个name与action里的File file 对应
onComplete:function(file,response){
if(response != ""){
$("#hiphoto").attr("src",response);//设置img的路径
$("#form1_userinfoTable_uphotourl").attr("value",response);//将路径同时设置在一个隐藏文本里
$(".img").val(response);//这个没发现有多大用
}
}
});)
请选择头像:
<img id="hiphoto" src="" width="76" height="76"/><br />
<input type="button" id="button1" name="btnupload" value="开始上传">
action中:
private String myfileFileName;
private File myfile;

public String getMyfileFileName() {
return myfileFileName;
}
public void setMyfileFileName(String myfileFileName) {
this.myfileFileName = myfileFileName;
}
public File getMyfile() {
return myfile;
}
public void setMyfile(File myfile) {
this.myfile = myfile;
}
//头像上传
public void loadImg() throws Exception{
Upload upload = new Upload();
upload.loadImg(myfileFileName,myfile);
}
把上传的那部分弄成了工具类:
public void loadImg(String fileFileName,File file) throws Exception{
String imgstr = saveFile(fileFileName, file);
responsePrt(imgstr);
}

private void responsePrt(String str){
try {
HttpServletResponse response =ServletActionContext.getResponse();
response.setContentType("text/html;charset=gbk");
response.setCharacterEncoding("gbk");//以上两句必须要
response.getWriter().println(str);
} catch (IOException e) {
e.printStackTrace();
}
}

public String saveFile(String fileFileName,File files) throws Exception{
String filename = "file_"+fileFileName;
String realpath=ServletActionContext.getServletContext().getRealPath("/upload");
File file= new File(realpath);
if(! file.exists()){
file.mkdirs();
}
FileUtils.copyFile(files, new File(file,filename));
//return realpath+"\\"+filename;
return "\\项目路径\\upload\\"+filename;
}从这边可以看到,action中声明的两个私有对象 myfileFileName、myfile是要和jsp页面中的name对应的,就是说name后面是什么名称,在action中就要以什么名称开头。即name:'XXX' 对应 private String XXXFileName,private File XXX;
还有要注意的是response中要先对其编码才能输出。

如此编码就可以实现题目所说的效果了。还有就是没有格式的过滤,也就后面试着了。

这个仅仅是单个文件上传,还有多个文件上传,要过几天尝试了。先记录着。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: