java web - 使用ajax的文件上传

//javascript
function insertPhoto(tValue){
var photofiles = '';
alert("123");
	if(tValue!=''){
	var len = tValue.length;
	var str = tValue.substr(tValue.lastIndexOf("."),len);
	if(str=='.jpg'||str=='.JPG'||str=='.gif'||str=='.GIF'||str=='.png'||str=='.PNG'||str=='.bmp'||str=='.BMP'){
			$('#imgpath').val(tValue);
			$.ajaxFileUpload({
                url:'',//用于文件上传的服务器端请求地址
                secureuri:false,//一般设置为false
                fileElementId:'file',//文件上传空间的id属性  <input type="file" id="file" name="file" />
                dataType : 'text',
                success: function(msg) {
					$('#imgid').attr("src",msg);
					$('#fimgpath').val(msg);
					$('#fileFileName').val(msg);
				}
            }); 	
	}else{
		 ZENG.msgbox.show("请选择 *.jpg *.gif *.png *.bmp 格式图片上传", 1, 2000);
		return false;
		}
	}
}

//jsp
        <tr>
	<th>上传图片:</th>
	<td  style="border-right-style:none">
	<html:text property="yingyezhizhao" ></html:text>
        <input type="file" name=file id="file" οnchange="if(this.value)insertPhoto(this.value);" hidefocus />
	<img src="<%=path %>/images/btn/xztp.gif" alt="添加" style="cursor:pointer"/>
        </td>
	<td style="border-left-style:none">
	<div id="imgpathTip" style="width:200px"/>
	</td>
	</tr> 

 //上传主图片
		public String uploadimg(){
			HttpServletResponse response = ServletActionContext.getResponse();
			try{
				String newName = "";
				if (file!=null&&file.getName().length() > 0) {
					int len = fileFileName.length();
					String pName = fileFileName.substring(fileFileName.lastIndexOf("."),len);
					//限制附件格式
					if(pName.equals(".jpg")||pName.equals(".gif")||pName.equals(".png")||pName.equals(".bmp") ||pName.equals(".JPG")||pName.equals(".GIF")||pName.equals(".PNG")||pName.equals(".BMP")){
						newName =  fileName(new Date()) +pName;
						String dir = ServletActionContext.getServletContext().getRealPath("images/fruit_talk/mainjx/");
						InputStream streamIn = new FileInputStream(file);
						OutputStream streamOut = new FileOutputStream(dir + "/" + newName);
						
						int bytesRead = 0;
						byte[] buffer = new byte[8192];
						while ((bytesRead = streamIn.read(buffer, 0, 8192)) != -1) {
							streamOut.write(buffer, 0, bytesRead);
						}
						streamOut.close();
						streamIn.close();
					}
				}
				
				response.setHeader("ContentType", "text/html");   
	            response.setContentType("text/html;charset=UTF-8"); 
				response.getWriter().write("images/fruit_talk/mainjx/"+newName); 
			}catch(Exception e){
				e.printStackTrace();
			}
			return null;
		}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值