我还在试着接受这件事。

我可以让用户选择文件(甚至多个)与文件输入:

<form>
  <div>
    <label>Select file to upload</label>
    <input type="file">
  </div>
  <button type="submit">Convert</button>
</form>

我可以用<填充事件处理程序>来捕获提交事件。但是一旦我这样做了,我如何使用fetch发送文件?

fetch('/files', {
  method: 'post',
  // what goes here? What is the "body" for this? content-type header?
}).then(/* whatever */);

当前回答

这是我的代码:

html:

const upload = (file) => { console.log(file); fetch('http://localhost:8080/files/uploadFile', { method: 'POST', // headers: { // //"Content-Disposition": "attachment; name='file'; filename='xml2.txt'", // "Content-Type": "multipart/form-data; boundary=BbC04y " //"multipart/mixed;boundary=gc0p4Jq0M2Yt08jU534c0p" // ή // multipart/form-data // }, body: file // This is your file object }).then( response => response.json() // if the response is a JSON object ).then( success => console.log(success) // Handle the success response object ).catch( error => console.log(error) // Handle the error response object ); //cvForm.submit(); }; const onSelectFile = () => upload(uploadCvInput.files[0]); uploadCvInput.addEventListener('change', onSelectFile, false); <form id="cv_form" style="display: none;" enctype="multipart/form-data"> <input id="uploadCV" type="file" name="file"/> <button type="submit" id="upload_btn">upload</button> </form> <ul class="dropdown-menu"> <li class="nav-item"><a class="nav-link" href="#" id="upload">UPLOAD CV</a></li> <li class="nav-item"><a class="nav-link" href="#" id="download">DOWNLOAD CV</a></li> </ul>

其他回答

这是我的代码:

html:

const upload = (file) => { console.log(file); fetch('http://localhost:8080/files/uploadFile', { method: 'POST', // headers: { // //"Content-Disposition": "attachment; name='file'; filename='xml2.txt'", // "Content-Type": "multipart/form-data; boundary=BbC04y " //"multipart/mixed;boundary=gc0p4Jq0M2Yt08jU534c0p" // ή // multipart/form-data // }, body: file // This is your file object }).then( response => response.json() // if the response is a JSON object ).then( success => console.log(success) // Handle the success response object ).catch( error => console.log(error) // Handle the error response object ); //cvForm.submit(); }; const onSelectFile = () => upload(uploadCvInput.files[0]); uploadCvInput.addEventListener('change', onSelectFile, false); <form id="cv_form" style="display: none;" enctype="multipart/form-data"> <input id="uploadCV" type="file" name="file"/> <button type="submit" id="upload_btn">upload</button> </form> <ul class="dropdown-menu"> <li class="nav-item"><a class="nav-link" href="#" id="upload">UPLOAD CV</a></li> <li class="nav-item"><a class="nav-link" href="#" id="download">DOWNLOAD CV</a></li> </ul>

添加php端点示例会很好。 这就是js:

const uploadinput = document.querySelector('#uploadinputid');
const uploadBtn = document.querySelector('#uploadBtnid');
uploadBtn.addEventListener('click',uploadFile);

async function uploadFile(){
    const formData = new FormData();
    formData.append('nameusedinFormData',uploadinput.files[0]);    
    try{
        const response = await fetch('server.php',{
            method:'POST',
            body:formData
        } );
        const result = await response.json();
        console.log(result);
    }catch(e){
        console.log(e);

    }
}

这就是php:

$file = $_FILES['nameusedinFormData'];
$temp = $file['tmp_name'];
$target_file = './targetfilename.jpg';
move_uploaded_file($_FILES["image"]["tmp_name"], $target_file);

如何上传一个文件选择使用HTML5获取

<label role="button">
  Upload a picture
  <input accept="image/*" type="file" hidden />
</label>
const input = document.querySelector(`input[type="file"]`);

function upload() {
  fetch(uplaodURL, { method: "PUT", body: input.files[0] });
}

input.addEventListener("change", upload); 

对我来说,问题是我正在使用response.blob()填充表单数据。显然你不能这样做,至少用react native,所以我最终使用

data.append('fileData', {
  uri : pickerResponse.uri,
  type: pickerResponse.type,
  name: pickerResponse.fileName
 });

Fetch似乎可以识别该格式,并将文件发送到uri指向的位置。

使用Fetch API发送文件的一个重要注意事项

我们需要忽略Fetch请求的内容类型头。然后浏览器会自动添加内容类型头,包括表单边界,看起来像

Content-Type: multipart/form-data; boundary=—-WebKitFormBoundaryfgtsKTYLsT7PNUVD

表单边界是表单数据的分隔符