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

从昨天到今天弄了好久,网上找的还是不是很全面。有些代码看的不清不楚的。有点费解。

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

先贴代码,

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中要先对其编码才能输出。

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

这个仅仅是单个文件上传,还有多个文件上传,要过几天尝试了。先记录着。






评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值