1、XMLHttpRequest升级版已经实现了跨域请求。不过需要在后台设置:header("Access-Control-Allow-Origin:http://www.a.com");表示某个域下允许跨域访问。
2、IE:需要使用XDomainRequest()。同样需要在后台设置:response.addHeader("Access-Control-Allow-Origin","*");
3、如果后台语言为java的话,需要自己写一个CrossDomainFilter,在过滤器中设置跨域访问,否则上传不成功。
下面以一个ajax文件上传的例子来说明跨域问题:
前台代码:
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="UTF-8"> 5 <title></title> 6 </head> 7 <body> 8 <form action="" method="post" onsubmit="return false;"> 9 <input type="file" name="myFile" id="myFile" value=""/> 10 <input type="button" id="btn" value="上传" /><br /> 11 </form> 12 <progress id="progress" max="100" value="0" style="margin-top:10px;"></progress> 13 </body> 14 </html> 15 <script type="text/javascript"> 16 window.onload = function(){ 17 var oBtn = document.getElementById("btn"); 18 var oFile = document.getElementById("myFile"); 19 var oProgress = document.getElementById("progress"); 20 oBtn.onclick = function(){ 21 if(oFile.files.length <=0)return; 22 //TODO:这里假定只是单文件上传 23 var formData = new FormData(); 24 formData.append("file",oFile.files[0]); 25 26 var xhr = new XMLHttpRequest(); 27 xhr.upload.onprogress = function(ev){ 28 ev = ev || window.event; 29 if(ev.lengthComputable)oProgress.value = parseInt(ev.loaded/ev.total*100); 30 } 31 xhr.upload.onload = function(){ 32 oProgress.value = 100; 33 } 34 xhr.open("POST","http://127.0.0.1:8080/ajax5.do",true); 35 xhr.send(formData); 36 } 37 38 } 39 </script>
后台代码:
1 package com.sgepit.ajax; 2 3 import java.io.File; 4 import java.io.IOException; 5 import java.util.List; 6 import java.util.UUID; 7 8 import javax.servlet.ServletException; 9 import javax.servlet.annotation.WebServlet; 10 import javax.servlet.http.HttpServlet; 11 import javax.servlet.http.HttpServletRequest; 12 import javax.servlet.http.HttpServletResponse; 13 import javax.servlet.http.HttpSessionContext; 14 15 import org.apache.commons.fileupload.FileItem; 16 import org.apache.commons.fileupload.disk.DiskFileItemFactory; 17 import org.apache.commons.fileupload.servlet.ServletFileUpload; 18 19 20 /** 21 * @author tengri 22 *文件上传 23 */ 24 @SuppressWarnings("all") 25 @WebServlet("/ajax5.do") 26 public class Ajax5 extends HttpServlet { 27 28 @Override 29 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 30 this.doPost(req, resp); 31 } 32 33 @Override 34 protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 35 DiskFileItemFactory factory = new DiskFileItemFactory(); 36 factory.setSizeThreshold(2014 * 1024); 37 factory.setRepository(new File("D:/uploadTemp")); 38 ServletFileUpload upload = new ServletFileUpload(factory); 39 resp.setCharacterEncoding("utf-8"); 40 try { 41 List<FileItem> items = upload.parseRequest(req); 42 for(FileItem item : items){ 43 if(!item.isFormField()){ 44 //文件名 45 String fileName = item.getName(); 46 System.out.println(new String(fileName.getBytes(),"utf-8")); 47 fileName = new String(fileName.getBytes(),"utf-8"); 48 //检查文件格式 49 String fileEnd = fileName.substring(fileName.lastIndexOf(".")+1).toLowerCase(); 50 //真实上传路径 51 StringBuffer sbRealPath = new StringBuffer(); 52 sbRealPath.append("D:/uploadFile/").append(fileName); 53 File file = new File(sbRealPath.toString()); 54 item.write(file); 55 } 56 } 57 } catch (Exception e) { 58 e.printStackTrace(); 59 } 60 } 61 62 }
过滤器:
package com.sgepit.ajax; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletResponse; /** * @author tengri *跨域filter */ public class CrossDomainFilter implements Filter{ public void destroy() { } public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException { HttpServletResponse res = (HttpServletResponse) resp; //这里最好不要写通配符,如果允许多个域请求数据的话,可以直接用逗号隔开:"http://www.baidu.com,http://google.com" res.setHeader("Access-Control-Allow-Origin", "*"); res.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS"); res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization, Accept,X-Requested-With"); chain.doFilter(req, resp); } public void init(FilterConfig arg0) throws ServletException { } }
web.xml配置过滤器:
1 <filter> 2 <filter-name>myFilter</filter-name> 3 <filter-class>com.sgepit.ajax.CrossDomainFilter</filter-class> 4 </filter> 5 <filter-mapping> 6 <filter-name>myFilter</filter-name> 7 <url-pattern>/*</url-pattern> 8 </filter-mapping>