NutzCN Logo
问答 文件上传跨域问题2,跨域烦恼
发布于 2548天前 作者 蛋蛋的忧伤 3685 次浏览 复制 上一个帖子 下一个帖子
标签:

我前两天出了个跨域问题,在入口函数上加了@Filters({@By(type=CrossOriginFilter.class)})这个注解就好了,但是我发现公司其他电脑访问时还是报错,报错如下:

跨域文件上传.html?_ijt=12dg1elorv6b1ia3633e8njf4:1 XMLHttpRequest cannot load http://10.2.1.102:8080/mychat/upload/image. Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. Origin 'http://localhost:63342' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

但是我在我本地的webstrom里访问是没问题的,按道理讲都是跨域,应该没区别吧,可为何其他电脑就报错呢?我服务端日志:

2017-05-06 14:04:06,553 org.nutz.mvc.impl.UrlMappingImpl.get(UrlMappingImpl.java:101) DEBUG - Found mapping for [OPTIONS] path=/upload/image : UploadModule.image(UploadModule.java:48)
2017-05-06 14:04:06,554 org.nutz.ioc.impl.NutIoc.get(NutIoc.java:151) DEBUG - Get 'uploadModule'<class com.mychat.controol.UploadModule>
2017-05-06 14:04:06,554 org.nutz.mvc.filter.CrossOriginFilter.match(CrossOriginFilter.java:49) DEBUG - Feedback -- [*] [get, post, put, delete, options] [origin, content-type, accept] [true]
2017-05-06 14:04:06,554 com.mychat.mvc.LogTimeProcessor.process(LogTimeProcessor.java:29) DEBUG - [OPTIONS]URI=/mychat/upload/image 1ms

我入口函数为:

@IocBean
@At("/upload")
@Ok("json")
public class UploadModule {
	/**
	 * 发送图片,上传图片接口
	 * @param file
	 * @param context
	 * @return
	 */
	@At
	@Filters({@By(type=CrossOriginFilter.class)})
	@AdaptBy(type = UploadAdaptor.class, args = { "${app.root}/WEB-INF/tmp" })
	public Object image(@Param("file") TempFile file,ServletContext context){
		System.out.println(file.getName());
		System.out.println(file.getMeta().getFileLocalName());
		InputStream in = null;
		OutputStream out = null;
		File f = file.getFile();
//		System.out.println("目录:"+context.getContextPath());	//获取项目名
//		System.out.println("目录2:"+context.getRealPath("/"));
		String tomcatPath =context.getRealPath("/");//获取到tomcat位于系统的绝对磁盘路径,//此为:D:\apache-tomcat-8.0.36\webapps\mychat\
		tomcatPath = tomcatPath.substring(0,tomcatPath.length()-1);//此为:D:\apache-tomcat-8.0.36\webapps\mychat
		tomcatPath = tomcatPath.substring(0,tomcatPath.lastIndexOf("\\"));//此为:D:\apache-tomcat-8.0.36\webapps
		String relpath = tomcatPath+"\\upload\\"+file.getMeta().getFileLocalName(); // 此为: D:\\apache-tomcat-8.0.36\\webapps\\upload\\tomat.png
		System.out.println("tomcatPath:"+tomcatPath);
		
//		String relpath = context.getRealPath("upload")+"\\"+file.getMeta().getFileLocalName();
		try {
			in = new FileInputStream(file.getFile());
			out = new FileOutputStream(relpath);
			byte[] buf = new byte[1024];
			int len = 0;
			while((len = in.read(buf))!=-1){
				out.write(buf,0,buf.length);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally{
			try {
				out.close();
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		
		String url ="/upload/"+file.getMeta().getFileLocalName();	//eclipse默认的tomcat目录是在其缓存文件中,你要自己指定到tomcat所在目录
		System.out.println(url);
		//构建json数据
		Map<String,Object> data = new HashMap<String,Object>();
		data.put("code", "0");
		data.put("msg", "");
		Map<String,String> sourceUrl = new HashMap<String,String>();
		sourceUrl.put("src", url);
		data.put("data", sourceUrl);
		
		return data;
	}

这当如何是好

13 回复

另外,既然是其他机器,怎么还是localhost

我本地访问时是没问题的,是其他电脑访问有跨域问题.

同事的js为:

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="webuploader/webuploader.css">
</head>
<body>

<!--dom结构部分-->
<div id="uploader-demo">
    <!--用来存放item-->
    <div id="fileList" class="uploader-list"></div>
    <div id="filePicker">选择图片</div>
</div>

<script src="js/jquery-1.11.1.js"></script>
<script src="webuploader/webuploader.js"></script>
<script>
    // 初始化Web Uploader
    var uploader = WebUploader.create({

        // 选完文件后,是否自动上传。
        auto: true,

//        // swf文件路径
//        swf: BASE_URL + '/js/Uploader.swf',

        // 文件接收服务端。
        server: 'http://10.2.1.102:8080/mychat/upload/image',

        // 选择文件的按钮。可选。
        // 内部根据当前运行是创建,可能是input元素,也可能是flash.
        pick: '#filePicker',

//        prepareNextFile:true,
//        chunked: true,  // 分片上传大文件
//        chunkRetry: 10, // 如果某个分片由于网络问题出错,允许自动重传多少次?
//        thread: 100,// 最大上传并发数
        method: 'POST',
        // 只允许选择图片文件。
        accept: {
            title: 'Images',
            extensions: 'gif,jpg,jpeg,bmp,png',
            mimeTypes: 'image/*'
        }
    });
    uploader.on( 'uploadSuccess', function( file ) {
       alert("已上传")
    });

    uploader.on( 'uploadError', function( file ) {
        $( '#'+file.id ).find('p.state').text('上传出错');
    });

    uploader.on( 'uploadComplete', function( file ) {
        $( '#'+file.id ).find('.progress').fadeOut();
    });
</script>
</body>
</html>

你贴的报错并非写这个ip

http://localhost:63342 这个报错ip是我同事电脑打开的,在webstrom打开的页面,端口为webstrom提供的.

127.0.0.1不是本地地址吗,我同事是写前台的,现在他要在她电脑访问我的tomcat,还能用127.0.0.1码???

我的意思是: 我朋友的电脑里的页面,发ajax访问我的电脑tomcat下的一个文件上传接口,但是出现了跨域,报了错.....

所以她访问的地址改一下啊,从现在的 http://localhost:66349 改成用 http://127.0.0.1:66349 来访问

不晓得为啥localhost跨域不了,但127.0.0.1可以

哎不是, 在他电脑上访问location或者127.0.0.1能访问到我的tomcat吗? tomcat在我电脑上哎,不应该我的局域网ip地址么?

静态页面是访问他们本地的文件(127.0.0.1),然后这些静态文件里js跨域访问了你机器上tomcat接口(某个内网ip),不是这样吗?

添加回复
请先登陆
回到顶部