dongshimao7115
dongshimao7115
2016-04-13 19:25

设置跨域文件上传的响应头和请求头

已采纳

I'm trying to upload a file from localhost:8888 to www.base.com . When the upload starts I have this error

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote 
resource at http://base.com/public_upload. (Reason: missing token 'x-file-name' 
in CORS header 'Access-Control-Allow-Headers' from CORS preflight channel).

Here are the header responses from php server that I set

header('Access-Control-Allow-Origin: http://localhost:8888');
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");

And here is the request header in upload script which runs in browser hosted by localhost:8888

xhr.setRequestHeader("Content-Type", "multipart/form-data"); 
xhr.setRequestHeader("X-File-Name", unescape(encodeURIComponent(file.name)));
xhr.setRequestHeader("X-File-Size", file.size);
xhr.setRequestHeader("X-File-Type", file.type);

What headers I've could mis-configed to create such error message?

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • dtkmejg127475 dtkmejg127475 5年前

    You have to add X-File-Name, X-File-Size and X-File-Type to the list of headers:

    header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, X-File-Name, X-File-Size, X-File-Type");
    

    Removing the Access-Control-Allow-Headers header should work too.

    点赞 评论 复制链接分享

相关推荐