HarmonyOS 鸿蒙Next 使用axios上传图片成功后回调内response.data为空
HarmonyOS 鸿蒙Next 使用axios上传图片成功后回调内response.data为空
在使用axios通过基于springboot的若依后台管理系统的通用文件上传接口上传文件成功后,回调response.data为空,代码如下
import axios, { AxiosError, AxiosProgressEvent, AxiosResponse, FormData } from '@ohos/axios'
import { WebUriEnum } from '../appenum/WebUriEnum';
import fs from '@ohos/file.fs';
export default class HttpUtil {
private static uploadInstance = axios.create({
baseURL: WebUriEnum.BASEUl,
timeout: 5000,
headers: {
'X-Custom-Header': 'foobar',
'Content-Type': 'multipart/form-data;charset=utf-8',
'Accept':'application/json'
}
})
public static upload<T, R>(token: string,formData:FormData,context:Context):Promise<AxiosResponse<R>>{
return new Promise<AxiosResponse<R>>((resolve, reject)=>{
this.uploadInstance.post<T, AxiosResponse<R>, FormData>(`${WebUriEnum.BASEUl}/common/upload`, formData, {
headers: {
Authorization: token
},
context:context,
onUploadProgress: (progressEvent: AxiosProgressEvent): void => {
console.info(progressEvent && progressEvent.loaded && progressEvent.total ? Math.ceil(progressEvent.loaded / progressEvent.total * 100) + '%--------------' : '0%--------------');
},
}).then((response) => {
fs.unlink(formData.get("file"))
resolve(response)
}).catch((err: AxiosError) => {
reject(err)
})
})
}
}
文件选择部分如下
public static selectPhotos(type: picker.PhotoViewMIMETypes, num: number): Promise<Array<string>> {
return new Promise<Array<string>>((resolve, reject) => {
const photoSelectOptions = new picker.PhotoSelectOptions();
photoSelectOptions.MIMEType = type; // 过滤选择媒体文件类型为IMAGE
photoSelectOptions.maxSelectNumber = num; // 选择媒体文件的最大数目
const photoViewPicker = new picker.PhotoViewPicker();
photoViewPicker.select(photoSelectOptions).then((photoSelectResult) => {
resolve(photoSelectResult.photoUris)
}).catch((err) => {
reject(err)
})
})
}
文件复制如下
public static FileOpen(fileuri:string):Promise<fs.File>{
return new Promise<fs.File>((resolve,reject)=>{
console.log('applog:fileuri:'+fileuri);
fs.open(fileuri, fs.OpenMode.READ_WRITE).then((file) => {
console.info("applog:file fd: "+file.fd);
resolve(file)
}).catch((err) => {
console.info("applog:open file failed with error message: "+err.message+", error code: "+err.code);
reject(err)
});
})
}
public static FileCopy(context:Context,file:fs.File,newFileName:string):Promise<string>{
return new Promise<string>((resolve,reject)=>{
let newpath = context.cacheDir + `/${newFileName}`;
fs.copyFile(file.fd, newpath).then(() => {
console.info("applog:copy file succeed");
fs.close(file)
resolve(newpath)
}).catch((err) => {
console.info("applog:copy file failed with error message: "+err.message+", error code: "+err.code);
reject(err)
});
})
}
在点击按钮后调用文件选择,更新avatarUri变量
FileSelectTool.selectPhotos(picker.PhotoViewMIMETypes.IMAGE_TYPE, 1).then((result) => {
this.avatarUri = result[0]
})
点击上传按钮后执行如下操作,将文件从公共相册复制到自己的沙盒目录,上传沙盒目录中的文件
let file =await FileReadUtil.FileOpen(this.avatarUri)
let newFilePath=await FileReadUtil.FileCopy(getContext(),file,`avatar_${this.userId}.png`)
let formData = new FormData()
formData.append('file', `internal://cache/avatar_${this.userId}.png`)
// formData.append('file', cacheDir + '/hello.txt'); uri支持传入沙箱路径
// 发送请求
let response = await HttpUtil.upload<ResultFileUploadBean,ResultFileUploadBean>(token,formData,getContext(this))
console.log(response.status+'---------------s')
console.log(response.statusText+'---------------t')
console.log(response.headers+'---------------a')
console.log(response.request+'---------------')
this.msg=response.data.msg
上传完成后在服务端所设置的本地文件目录中能找打它,也能通过服务端输出的uri进行下载,但是上方代码response.data为空
若依后台管理系统文件上传接口如下,路径会被自动拼接上common,所以是/common/upload
package com.ruoyi.web.controller.common;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.framework.config.ServerConfig;
/**
* 通用请求处理
*
* @author ruoyi
*/
@RestController
@RequestMapping("/common")
public class CommonController
{
private static final Logger log = LoggerFactory.getLogger(CommonController.class);
@Autowired
private ServerConfig serverConfig;
private static final String FILE_DELIMETER = ",";
/**
* 通用上传请求(单个)
*/
@PostMapping("/upload")
public AjaxResult uploadFile( MultipartFile file) throws Exception
{
try
{
System.out.println(file.getName());
// 上传文件路径
String filePath = RuoYiConfig.getUploadPath();
// 上传并返回新文件名称
String fileName = FileUploadUtils.upload(filePath, file);
String url = serverConfig.getUrl() + fileName;
AjaxResult ajax = AjaxResult.success();
ajax.put("url", url);
ajax.put("fileName", fileName);
ajax.put("newFileName", FileUtils.getName(fileName));
ajax.put("originalFilename", file.getOriginalFilename());
return ajax;
}
catch (Exception e)
{
return AjaxResult.error(e.getMessage());
}
}
}
AjaxResult内部结构如下
package com.ruoyi.common.core.domain;
import java.util.HashMap;
import java.util.Objects;
import com.ruoyi.common.constant.HttpStatus;
import com.ruoyi.common.utils.StringUtils;
/**
* 操作消息提醒
*
* @author ruoyi
*/
public class AjaxResult extends HashMap<String, Object>
{
private static final long serialVersionUID = 1L;
/** 状态码 */
public static final String CODE_TAG = "code";
/** 返回内容 */
public static final String MSG_TAG = "msg";
/** 数据对象 */
public static final String DATA_TAG = "data";
/**
* 初始化一个新创建的 AjaxResult 对象,使其表示一个空消息。
*/
public AjaxResult()
{
}
/**
* 初始化一个新创建的 AjaxResult 对象
*
* @param code 状态码
* @param msg 返回内容
*/
public AjaxResult(int code, String msg)
{
super.put(CODE_TAG, code);
super.put(MSG_TAG, msg);
}
/**
* 初始化一个新创建的 AjaxResult 对象
*
* @param code 状态码
* @param msg 返回内容
* @param data 数据对象
*/
public AjaxResult(int code, String msg, Object data)
{
super.put(CODE_TAG, code);
super.put(MSG_TAG, msg);
if (StringUtils.isNotNull(data))
{
super.put(DATA_TAG, data);
}
}
/**
* 方便链式调用
*
* @param key 键
* @param value 值
* @return 数据对象
*/
@Override
public AjaxResult put(String key, Object value)
{
super.put(key, value);
return this;
}
}
请大佬帮忙看看为什么文件上传成功但是response.data会为空
更多关于HarmonyOS 鸿蒙Next 使用axios上传图片成功后回调内response.data为空的实战教程也可以访问 https://www.itying.com/category-93-b0.html
一样也遇到这个问题,axios上传文件成功,但是没有返回结果
更多关于HarmonyOS 鸿蒙Next 使用axios上传图片成功后回调内response.data为空的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html
建议排查思路
- 先加一个axios的response响应拦截器,看一下拦截器里面是返回正确还是直接进入catch
第二步可以参考一下eftooleftool的Axiosutil地址的AxiosUtil和与之对应的后端Java代码对应地址
希望可以提供思路
针对帖子标题“HarmonyOS 鸿蒙Next 使用axios上传图片成功后回调内response.data为空”的问题,以下是专业回答:
在HarmonyOS鸿蒙Next系统中,使用axios上传图片后,如果回调中response.data
为空,可能的原因包括但不限于以下几点:
-
服务器响应问题:服务器端在处理图片上传请求后,可能未正确返回数据或返回的数据为空。检查服务器端的处理逻辑,确保在图片上传成功后有返回有效数据。
-
axios配置问题:检查axios的配置,确保请求类型、请求头、数据格式等设置正确。特别是
responseType
字段,如果服务器返回的是非JSON格式数据(如文件流),需要设置正确的responseType
。 -
跨域问题:如果图片上传请求涉及跨域,确保服务器支持CORS(跨来源资源共享),并且客户端axios请求中配置了正确的跨域设置。
-
网络问题:网络延迟或中断可能导致客户端未能正确接收服务器返回的数据。检查网络连接状态,确保网络通畅。
如果上述检查均无误,但问题依旧存在,可能是由于HarmonyOS鸿蒙Next系统特有的兼容性问题或axios库的bug导致。此时,建议尝试更新axios库版本或查阅HarmonyOS鸿蒙Next系统的相关文档和社区,以获取更多帮助。
如果问题依旧没法解决请联系官网客服,官网地址是:https://www.itying.com/category-93-b0.html,