我有一个redux-from提交,控制台日志如下所示
{
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"
答案 0 :(得分:1)
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
}
答案 1 :(得分:1)
对于获取API,您可以尝试
func getTimeFromServer(completionHandler:@escaping (_ getResDate: Date?) -> Void){
let url = URL(string: "https://www.apple.com")
let task = URLSession.shared.dataTask(with: url!) {(data, response, error) in
let httpResponse = response as? HTTPURLResponse
if let contentType = httpResponse!.allHeaderFields["Date"] as? String {
//print(httpResponse)
let dFormatter = DateFormatter()
dFormatter.dateFormat = "EEE, dd MMM yyyy HH:mm:ss z"
let serverTime = dFormatter.date(from: contentType)
completionHandler(serverTime)
}
}
task.resume()
}
答案 2 :(得分:0)
首先是将fetch api
用于帖子content-type header
时应与type body
相匹配。由于您的身体为json stringified
,因此您的 contentType 标头应为'application/json'
。 more about this。
第二。由于您要上传file
的图片,因此无需设置contentType即可使用FormData,例如以下:
let formData = new FormData();
formData.append('logo', image.logo[0]);
const requestOptions = {
method: 'POST',
body: formData
};
fetch(`${apiUrl}/API`, requestOptions)
.then(handleResponse)...
答案 3 :(得分:0)
移动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; });
}