在JS中使用formdata和fetchAPI将表单上传的图片发送到服务器

Tai*_*are 1 javascript forms fetch image-upload

我正在尝试从单个表单中提取图像和文本数据。我尝试使用 formdata.get('image') 来获取用户选择的图像,但它不起作用,因为我在服务器上收到未定义的值。我想知道使用 formdata 或任何其他方法获取用户在表单中选择的图像的适当方法,谢谢。

表格

 <form id = "register" class = "edit-note" enctype = "multipart/form-data">
                <div>
                    <label>Heading:</label>
                    <input type = "text" name = "heading" placeholder = "<%= Note[0].heading %>" id = "heading">
                </div>
                <div>
                    <label>Small Text:</label>  
                    <input type = "text" name = "stext" placeholder = "<%= Note[0].smallText %>" id = "stext">
                </div>

                <div>
                    <label>Featured Image:</label>
                    <img src = "<%= Note[0].image %>" height = "110px" width = "132px">
                    <input type = "file" name = "image" id = "fimage">
                </div>
                <div>
                    <label>Background Image:</label>
                    <img src = "<%= Note[0].background %>" height = "110px" width = "132px">
                    <input type = "file" name = "bimage" id = "bimage">
                </div>
    
                <div>
                    <label>Content:</label> 
                    <textarea name = "content" placeholder = "<%= Note[0].content %>" id = "content"></textarea>
                </div>

                <input type = "submit" name = "register" value = "Save Changes">
            </form>
Run Code Online (Sandbox Code Playgroud)

获取API

const noteForm = document.querySelector('.edit-note');

noteForm.addEventListener('submit', function(e) {
    e.preventDefault();
    let url = "";

    const formData = new FormData(this);

    fetch( '/images', {
        method: 'POST',
        body: formData.get('image')
    }).then(response => {
        response.json();
    }).then(URL => {
        //console.log(URL);
        url = URL;
Run Code Online (Sandbox Code Playgroud)

我排除了与问题无关的 FetchAPI 部分。

May*_*eyz 5

如果您想使用 then 上传文件,XMLHttpRequest则必须使用FormData您正在执行的操作,但方式不正确。

第一步:创建FormData实例

let formData = new FormData();
Run Code Online (Sandbox Code Playgroud)

步骤 - II:追加其中的数据

formData.append('file_to_upload', fileField.files[0]);  // Here fileField is the input file reference
Run Code Online (Sandbox Code Playgroud)

第三步:发送formData出去XMLHttpRequest,您将获得您在附加到 时提供的名称的文件formData,在上面的情况下是 -file_to_upload