开发者社区> 问答> 正文

求助大神,bootstrap fileinput上传图片不执行回调函数,并且会报错?报错

求助大神,项目中用到了bootstrap fileinput+struts2,写好后端上传函数之后图片能够上传,但是回调函数不执行,而且前端还会报错,如下:

HTML代码:

			<div class="col-xs-12">
				<input type="file" name="img" id="img" value="" multiple="multiple"
					data-show-preview="true" />
			</div>

JS代码:

$("#img").fileinput({
		language : 'zh',
		uploadUrl : "uploadImg",
		showCaption : true,
		showRemove : true,
		uploadAsync : true,
		showPreview : true,
		textEncoding : "UTF-8",
		autoReplaceBoolean : false,
	});
	
	$("#img").on('fileuploaded', function(event, data, previewId, index) {
		alert(data);
	});
		
	$("#img").on('filebatchuploadsuccess', function(event, data, previewId, index) {
		alert(data);
	});
	
	$("#img").on('fileerror', function(event, data, msg) {
		alert(data);
	});

javaAction:

	public void uploadImg(){
		String imgPath=UploadUtil.uploadImg(getImg(), getImgFileName());
		HttpServletResponse response=ServletActionContext.getResponse();
		PrintWriter out=null;
		String jsonString="{'imgUrl':'"+imgPath+"'}";
		try {
			out=response.getWriter();
			out.print(jsonString);
			out.flush();
			out.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

UploadUtil代码:

	public static String uploadImg(File img,String imgFileName) {
		String folderPath="";
		String imgUrl = "";//返回的图片地址
		HttpServletRequest request = ServletActionContext.getRequest();//获取request对象
		StringBuffer url1 = request.getRequestURL();//获取当前页面的URL
		String tempContextUrl1 = url1.delete(url1.length() - request.getRequestURI().length(), url1.length())
				.append("/").toString();//当前页面的URL减去当前页面的地址为http头
		String p = request.getRealPath("/img/upload");//得到站点的绝对地址
		String path;
		String fileName = UUID.randomUUID().toString() + imgFileName.substring(imgFileName.lastIndexOf("."));//生成随机图片名称
		int length;
		path = p + "\\" + fileName;//图片地址全
		try {
			FileOutputStream fos = new FileOutputStream(path);
			FileInputStream fis = new FileInputStream(img);
			byte[] buffer = new byte[1024 * 1024 * 20];
			while ((length = fis.read(buffer)) > 0) {
				fos.write(buffer, 0, length);
			}
			fos.close();
			fis.close();

			imgUrl = tempContextUrl1 + request.getContextPath() + "/img/upload/" + fileName;
		} catch (FileNotFoundException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		} catch (IOException e) {
			// TODO 自动生成的 catch 块
			e.printStackTrace();
		}
		return imgUrl; // 返回url地址
	}

图片上传执行之后图片能够上传,但是好像返回数据出了点问题,而且也不执行回调函数,求助各位大神,感谢!!!

展开
收起
爱吃鱼的程序员 2020-06-06 20:48:01 929 0
1 条回答
写回答
取消 提交回答
  • https://developer.aliyun.com/profile/5yerqm5bn5yqg?spm=a2c6h.12873639.0.0.6eae304abcjaIB
                        <p>图中给出了问题,说是json格式有问题出现了'(单引号),试试双引号呗,大兄弟。</p>
    
    2020-06-06 20:48:14
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
低代码开发师(初级)实战教程 立即下载
冬季实战营第三期:MySQL数据库进阶实战 立即下载
阿里巴巴DevOps 最佳实践手册 立即下载