当前位置: 代码迷 >> JavaScript >> 如何在Node.js中检索上层文件
  详细解决方案

如何在Node.js中检索上层文件

热度:94   发布时间:2023-06-05 09:31:58.0

我有一个来自提交的redux,控制台日志看起来像这样

{
  id: "x", 
  parentId: "b", 
  editing: true, 
  logo: FileList, 
}

我认为徽标FileList包含我上传的文件名和文件

0: File(19355) {name: "11964821.jpeg", lastModified: ......

使用获取发送到nodejs,图像包含我的文件和上述数据

function Update(image) {

    const requestOptions = {
        method: 'POST',
        headers: { ...authHeader(), 'Content-Type': 'application/x-www-form-urlencoded' },
        body: JSON.stringify(image)
    };
    return fetch(`${apiUrl}/API`, requestOptions).then(handleResponse)
    .then( data => {  return data; });
}

但是此数据未接收到nodejs,因为尝试了re.file等。其显示未定义

app.post('/image', upload.single('logo'), function (req, res, next) {

})


包括表格数据

  const onSubmit = (image, dispatch)=>{ var formData = new FormData(); formData.append('logo',image.logo[0]); var imageNew = {...image,formData}; dispatch(imageActions.companyProfileLogoUpdate(imageNew)) ; } 

现在日志

 formData: FormData {} id: "5c66478b0814720a4365fe72" logo: FileList {0: File(19355), length: 1} parentId: "5c66478b0814720a4365fe71" 
let formData = new FormData();
formData.append('logo' , {{your image file}}

// upload file as 
let result = await sendServerRequestForForm(url,formData);


function sendServerRequestForForm(url,data) {
var promise = new Promise(function(resolve) {
    resolve($.ajax({
        url,
        method : 'POST',
        data,
        processData: false,
        contentType: false,
        success: function(data) {
            return data
        },
        error: function (err) {
            try{
                let responseStatus = err.responseJSON
                // watch your response
            }catch (e) {
                console.log('Field to get response');
            }
        }
    }));
});
return promise

}

对于获取API,您可以尝试此

let formData = new FormData();
formData.append('logo', fileList[0]);

fetch(url, {
method: 'post',
body: data,
})
.then(…);

第一件事是使用fetch api来发布content-type header应与typeof body匹配。 由于您的身体是json stringified的,因此contentType标头应为'application/json'

第二 因为你要上传的其中一个图像file ,你应该使用没有设置的contentType的要求:象下面这样:

let formData = new FormData();
formData.append('logo', image.logo[0]);

const requestOptions = {
  method: 'POST',
  body: formData
};

fetch(`${apiUrl}/API`, requestOptions)
.then(handleResponse)...

移动formData来获取文件并删除标题内容类型,请尝试以下操作

function Update(image) {

var formData = new FormData(); 
formData.append('logo',image.logo[0]);  

    const requestOptions = {
        method: 'POST',
        headers: { ...authHeader() },
        body: formData
    };
    return fetch(`${apiUrl}/API`, requestOptions).then(handleResponse)
    .then( data => {  return data; });
}
  相关解决方案