How does HTTP file upload work?

后端 未结 5 1543
不思量自难忘°
不思量自难忘° 2020-11-22 00:49

When I submit a simple form like this with a file attached:

5条回答
  •  野的像风
    2020-11-22 01:10

    Send file as binary content (upload without form or FormData)

    In the given answers/examples the file is (most likely) uploaded with a HTML form or using the FormData API. The file is only a part of the data sent in the request, hence the multipart/form-data Content-Type header.

    If you want to send the file as the only content then you can directly add it as the request body and you set the Content-Type header to the MIME type of the file you are sending. The file name can be added in the Content-Disposition header. You can upload like this:

    var xmlHttpRequest = new XMLHttpRequest();
    
    var file = ...file handle...
    var fileName = ...file name...
    var target = ...target...
    var mimeType = ...mime type...
    
    xmlHttpRequest.open('POST', target, true);
    xmlHttpRequest.setRequestHeader('Content-Type', mimeType);
    xmlHttpRequest.setRequestHeader('Content-Disposition', 'attachment; filename="' + fileName + '"');
    xmlHttpRequest.send(file);
    

    If you don't (want to) use forms and you are only interested in uploading one single file this is the easiest way to include your file in the request.

提交回复
热议问题