Dwr上传文件

前端之家收集整理的这篇文章主要介绍了Dwr上传文件前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

DWR 文件上传 Failed to find parameter: scriptSessionId

出现这种错误 , 是由于 dwr 在发送 request 的时候, 其被 Struts2的 filter 拦截

一般情况下是由于在 web.xml 中 Struts 的 url-pattern 写成 /* 了

<filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
   </filter-mapping

正确的写法是如下: Struts 只是拦截指定类型的请求

在 web.xml 中:

  <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>*.action</url-pattern>
   </filter-mapping>


  <servlet-mapping>
    <servlet-name>dwr-invoker</servlet-name>
    <url-pattern>/dwr/*</url-pattern>
  </servlet-mapping>


java

public String upload(InputStream inputStream,String filename)
			throws Exception {
		WebContext wc = WebContextFactory.get();
		HttpServletRequest req = wc.getHttpServletRequest();
		String realpath = req.getSession().getServletContext()
				.getRealPath("upload");
		String fn = FilenameUtils.getName(filename);
		String filepath = realpath + "/" + fn;
		FileUtils.copyInputStreamToFile(inputStream,new File(filepath));
		return filepath;
	}

jsp和js

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>My JSP 'index.jsp' starting page</title>
<script type="text/javascript" src="dwr/engine.js"></script>
<script type="text/javascript" src="dwr/util.js"></script>
<script type="text/javascript" src="dwr/interface/booksManage.js"></script>
<script type="text/javascript" src="js/myjavascript.js"></script>
<script type="text/javascript">
//使用dwr实现Ajax上传图片

function uploadImg() {
	var file =  dwr.util.getValue("imgFile");
	alert(file.value);
	alert(file);
	
	booksManage.upload(file,file.value,function(data){
		alert(data);
		$("img").src = "upload/"+file.value	;
	});
}
</script>
</head>

<body>
	选择图片<input type="file" id="imgFile"/><br/>
	<input type="button" id="uploadImgButton" value="上传" onclick="uploadImg()"/><br/>
	<img alt="" src="onepice.jpg" style="margin: 100px,auto; width: 100px;" id="img"/> 
</body>
</html>

猜你在找的Ajax相关文章