前端上传大文件,后端报错Content-Type ‘application/octet-stream‘ is not supported【解决】
-
- 报错内容
org.springframework.web.HttpMediaTypeNotSupportedException: Content-Type 'application/octet-stream' is not supported
- 报错内容
-
- 组件库:
naiveui
中upload
进行上传功能使用的主要组件
- 组件库:
-
- 使用原生
XMLHttpRequest
进行接口请求
- 使用原生
-
authorization
请求头需要手动写入
-
不需要手动配置请求头 文件格式类型 headers: { 'Content-Type': 'multipart/form-data' },
-
xhr.onreadystatechange
— 监听 readyState 变化
<script setup lang="tsx">
/**
* 上传固件文件变化
*
* @param data
*/
const handleUploadChange = (data: {
file: SettledFileInfo;
fileList: SettledFileInfo[];
event: ProgressEvent | Event | undefined;
}) => {
fileList.value = data.fileList;
fileData.value = data.file.file || undefined;
};
/** 上传固件 */
const upload = async () => {
const isHttpProxy = import.meta.env.DEV && import.meta.env.VITE_HTTP_PROXY === 'Y'; // 不同环境---域名不同
const { otherBaseURL } = getServiceBaseURL(import.meta.env, isHttpProxy);
const xhr = new XMLHttpRequest()
xhr.open('POST',otherBaseURL.aj+ '/monitor/ota/upgrade/upload', true);
xhr.onload = () => {
const response=JSON.parse(xhr.response)//response就是服务器返回的信息
}
const formData = new FormData()
formData.append("file", firmwareModel.value.file)//
formData.append("otaUpgrade", new Blob([JSON.stringify({
upgradePackageName: firmwareModel.value.upgradePackageName,
upgradeType: 1,
upgradeVersion: firmwareModel.value.upgradeVersion,
deviceClassificationId: props.details.deviceClassificationId,
middleClassId: props.details.middleClassId,
typeCodeId: props.details.typeCodeId,
isOldDevice: true,
remark: firmwareModel.value.remark,
packageType: props.details.packageType
})], { type: "application/json" }))
xhr.setRequestHeader('Authorization',window.sessionStorage.getItem('token'));
xhr.send(formData)//执行发送指令
// 监听 readyState 变化
xhr.onreadystatechange = function() {
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
// 解析响应数据
if(JSON.parse(xhr.response).status == -1){
message.success('上传成功')
}else{
message.error(JSON.parse(xhr.response).message);
}message 字段的值 // 输出: 已经存在同名的升级文件!
} else {
console.error('请求失败,状态码:', xhr.status);
}
}
};
submitLoading.value = false;
};
</script>
<template>
<NUpload
v-if="props.type === 'upload'"
v-model:file-list="fileList"
v-model:value="firmwareModel.file"
directory-dnd
multiple
:max="1"
@change="handleUploadChange"
>
<NUploadDragger>
<div class="upload-icon">
<NIcon size="48" :depth="3">
<Archive16Filled />
</NIcon>
</div>
<NText class="upload-content">点击或者拖动文件到该区域来上传</NText>
</NUploadDragger>
</NUpload>
<span v-if="props.type === 'edit'">{{ props.details.upgradePackageName }}</span>
</template>