Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

使用form-data上传文件boundary不一致的问题 #19

Open
791045873 opened this issue Mar 28, 2019 · 0 comments
Open

使用form-data上传文件boundary不一致的问题 #19

791045873 opened this issue Mar 28, 2019 · 0 comments

Comments

@791045873
Copy link
Owner

791045873 commented Mar 28, 2019

问题回顾与解决

在写一个上传文件的功能时,本想着就是几分钟的事,没想到一直上传不成功。

在我未显式设置content-type未form-data时,服务器报错:not found multipart。所以我手动设置content-type为multipart/form-data。
当我如此设置之后,服务器报错:not found boundary。
于是,我又在multipart/form-data后手动添加了boundary。服务器报错:file is not represent
经检查后发现,http request header中的boundary与body中的boundary不一致。
其中,http request header中的boundary是我手动设置的,但是body中的boundary是浏览器设置的。
于是,该问题变成了一个死循环。

为了解决问题,查看了rc-upload的源代码(阿里ant中upload组件依赖的一个基础库)。发现他们对xhr的header做了如下设置:

xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest')

如此设置后,浏览器便会自己填写对象的content-type与boundary了。于是,文件上传成功~

解决方案的深挖

在HTTP中,X开头的是扩展首部,X-Request-With用来区分请求是同步请求还是异步请求。
boundary是一个随机字符串,用来划分上传文件的内容。具体解释请看这里

// 关于解决方案的具体原理目前并没有查到,希望之后能有眉目吧

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant