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

html5 file api相关 , HTTP请求中的form data和request payload的区别 #58

Open
5Mi opened this issue Aug 23, 2016 · 3 comments
Open

Comments

@5Mi
Copy link
Owner

5Mi commented Aug 23, 2016

HTML5使用 JavaScript File API 实现文件上传

[JS进阶] HTML5 之文件操作(file)

javascript 使用Html5 File Api进行文件读取

还是不太熟..

通用模式,省的每次都得想下

 // 修改头像
    async handleHeadImage (e) {
      let file = e.target.files[0]
      if (!file) return
      const maxSize = 1024 * 1024 * 2
      if (!/image\/\w+/.test(file.type)) {
        return this.$toast('请选择图片')
      }
      if (file.size > maxSize) {
        return this.$toast(`上传图片不能超过${fmtSize(maxSize)}`)
      }
      try {
        this.$_app_Loading.show()
        let formData = new FormData()
        formData.append('upfile', file)
        let res = await savaPic(formData)
        if (!res) {
          this.$_app_Loading.hide()
          return this.$toast('上传图片失败')
        }
        // 调用修改
        let result = await editUserImgAndName({ openId: this.userInfo.openId, userId: this.userInfo.uid, avatarUrl: res })
        if (!result) {
          this.$_app_Loading.hide()
          return this.$toast('修改失败')
        }

        this.$store.commit('SET_USERINFO', { headImg: res })
        this.$toast('修改成功')
      } catch (e) {
        console.log(e)
      }
      e.target.value = ''
      this.$_app_Loading.hide()
    },
@5Mi
Copy link
Owner Author

5Mi commented Dec 27, 2017

HTTP请求中的form data和request payload的区别

AJAX Post请求中常用的两种传参数的形式:form data 和 request payload

form data

get请求的时候,我们的参数直接反映在url里面,形式为key1=value1&key2=value2形式,比如:
http://news.baidu.com/ns?word=NBA&tn=news&from=news&cl=2&rn=20&ct=1
如果是post请求,那么表单参数是在请求体中,也是以key1=value1&key2=value2的形式在请求体中
这里要注意post请求的Content-Type为application/x-www-form-urlencoded(默认的),参数是在请求体中,即Form Data。

request payload

请求的Content-Type为application/json;charset=UTF-8,而请求表单参数在Request Payload中

区别

参考:http://stackoverflow.com/questions/10494574/what-is-the-difference-between-form-data-and-request-payload

if a request (typically POST) has Content-type header set to application/x-www-form-urlencoded the body is expected to be in the form of a standard querystring with url-encoded key=value pairs joined by &. Form data section then shows the key-value parameters (when viewed parsed). This way was much more common in past because it is a default for HTML forms.
other cases are shown in Request payload section (and nowadays parsed for readability as well for common formats like JSON).

转自

@5Mi 5Mi changed the title html5 file api相关 html5 file api相关 , HTTP请求中的form data和request payload的区别 Dec 27, 2017
@5Mi
Copy link
Owner Author

5Mi commented Apr 4, 2018

为什么要设置Content-type

HTTP请求分为三个部分:状态行、请求头、消息主体。协议规定POST提交的数据必须放在消息主体中,但协议并没有规定数据必须使用什么编码方式。
实际上,开发者完全可以自己决定消息主体的格式,一般服务器端语言如PHP、Python等,都内置了自动解析常见数据格式的功能。服务器端是根据请求头中的Content-type字段来获知请求中的消息主体是用何种方式编码,再对主体进行解析。

而GET请求提交的数据以" key1=value1&key2=value2 "的格式附在URL之后,也就是在请求头中,不用设置Content-type字段。

常见Content-type

  • application/x-www-form-urlencoded:数据格式为"key1=value1&key2=value2"

  • multipart/form-data:用于传输文件

  • application/json:数据格式为json格式,有的服务器语言不支持(比如PHP,需要从php://input里获得原始输入流,再json_decode成对象。)

  • text/plain:纯文本传输,用得少

表单提交

form表单提交时,Content-type由enctype设置:

<!-- submit时页面跳转 -->
<form enctype="multipart/form-data" method="post"></form>

如果不设置enctype,默认为application/x-www-form-urlencoded
目前原生form只支持application/x-www-form-urlencodedmultipart/form-datatext/plain(HTML5)。

Ajax提交

Ajax的POST请求,Content-type默认为text/plain,需要根据具体传输的数据,使用

xhr.setRequestHeader("Content-type","...")
指定具体格式,但如果传送的是FormData格式的数据,会自动设置为multipart/form-data

来自

@5Mi
Copy link
Owner Author

5Mi commented Feb 14, 2020

js模拟form表单提交

/**
 * form表单提交
 * @param {*} url
 * @param {*} params
 */
function formPost(url, params) {
    const $form = document.createElement('form');
    $form.action = url;
    $form.style.display = 'none';
    $form.target = '_self';
    $form.method = 'post';
    for (let key in params) {
        let $input = document.createElement('input');
        $input.name = key;
        $input.value = params[key];
        $form.appendChild($input);
    }
    document.body.appendChild($form);
    $form.submit();
}

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

No branches or pull requests

1 participant