Flutter上传图片至Spring后端出现401错误,求解决办法
问题描述
Flutter端图片上传代码:
Future uploadFile() async { // 通过file picker选择文件 final filePath = _image!.path; // 通过文件路径生成formData var dio = ref.read(dioProvider); var formData = FormData.fromMap({ 'file' : await MultipartFile.fromFile(filePath!) }); dio.options.headers.addAll({ 'accessToken': 'true', }); // 上传请求 final response = await dio.post("http://$ip/s3/upload", data: formData,options: Options( contentType: 'multipart/form-data' )); _downloadUrl = response.data; print(response.statusCode.toString() + "hihi"); }
报错信息:
[ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: DioError [DioErrorType.response]: Http status error [401]
使用Spring服务器,发送图片上传请求时持续返回401未授权错误,以下是针对性解决方案:
解决方案
修正Token传递逻辑
- 你当前设置的
accessToken: 'true'是无效授权值,需替换为实际的用户授权Token。同时注意Spring后端常用的Token格式:- 若后端用
Authorization头,格式为Bearer {token},修改代码:dio.options.headers.addAll({ 'Authorization': 'Bearer 你的有效用户Token', }); - 若后端明确要求
accessToken作为头键,直接填入真实Token值即可,不要用true占位。
- 若后端用
- 你当前设置的
验证接口与Token有效性
- 用Postman直接调用
http://{ip}/s3/upload接口,携带正确Token,确认接口本身是否正常响应。 - 如果Postman也返回401,说明Token过期/无效,或用户无该接口访问权限,需重新生成有效Token,或在Spring权限配置中开放该接口权限。
- 用Postman直接调用
检查Spring Security配置
- 确认Spring后端是否将
/s3/upload接口加入白名单,避免被权限拦截;若需授权访问,确保Token对应的用户角色拥有该接口的访问权限。 - 检查跨域(CORS)配置,若前后端域名不同,需允许携带自定义请求头(如
Authorization或accessToken),示例配置:@Configuration public class CorsConfig implements WebMvcConfigurer { @Override public void addCorsMappings(CorsRegistry registry) { registry.addMapping("/**") .allowedOrigins("你的前端域名") .allowedMethods("POST") .allowedHeaders("Authorization", "accessToken") .allowCredentials(true); } }
- 确认Spring后端是否将
避免Dio Header冲突
- 若
dioProvider提供的Dio实例已预设Header,调用addAll可能导致覆盖或冲突,建议直接在请求级别设置Header:final response = await dio.post( "http://$ip/s3/upload", data: formData, options: Options( contentType: 'multipart/form-data', headers: { 'Authorization': 'Bearer 你的有效Token', }, ), );
- 若
排查Token生成与存储问题
- 若使用JWT Token,验证Token过期时间、签名密钥是否与后端一致(可通过JWT解析工具校验)。
- 确保前端登录后正确保存Token,上传时使用的是最新的有效Token,而非过期或错误的旧值。
内容的提问来源于stack exchange,提问作者LeeChangMin
相关产品推荐
相关产品推荐

