RestEasy上传文件的工具类
前言
RestEasy是比较老的技术,有挺多坑,非必要不建议使用。
网络上相关的资料也比较少,只能自己封装一个工具类。
RestEasy上传文件的资料,可以看一下: https://www.cnblogs.com/expiator/p/14590557.html
RestEasyUtil
import org.apache.commons.io.IOUtils;
import org.jboss.resteasy.plugins.providers.multipart.InputPart;
import javax.ws.rs.core.MediaType;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;
public class RestEasyUtil {
private RestEasyUtil(){ }
/**
* 文件名称
*/
public static final String FILE_NAME = "fileName";
/**
* 文件对应的字段名称
*/
public static final String FILE_DATA_NAME = "fileData";
/**
* 从formData中获取字段的值
*
* @param uploadForm form表单数据
* @param key 字段名
* @return
* @throws IOException
*/
public static String getValueFromBody(Map<String, List<InputPart>> uploadForm, String key) {
return getValueWithDefault(uploadForm, key, "");
}
/**
* 从formData中获取字段的值,设置默认值。
*
* @param uploadForm
* @param key
* @param defaultValue
* @return
* @throws IOException
*/
public static String getValueWithDefault(Map<String, List<InputPart>> uploadForm, String key, String defaultValue) {
String value = defaultValue;
try {
InputPart inputPart = uploadForm.get(key).get(0);
inputPart.setMediaType(MediaType.TEXT_PLAIN_TYPE);
value = inputPart.getBodyAsString();
} catch (Exception e) {
log.error("getValueFromBody.lack of key: {}", key);
log.error("getValueFromBody catch exception.", e );
}
return value;
}
/**
* 获取文件的流
*
* @param uploadForm form表单数据
* @param fileDataName 文件对应的字段名称
* @return
* @throws IOException
*/
public static InputStream getInputStreamFromBody (Map<String, List<InputPart>> uploadForm, String fileDataName) throws IOException {
List<InputPart> inputParts = uploadForm.get(fileDataName);
InputPart inputPart = inputParts.get(0);
return inputPart.getBody(InputStream.class, null);
}
/**
* 获取完整的数据流
* 默认的数据流只有1024字节,需要重新生成包含所有字节的 ByteArrayInputStream 数据流。
*
* @param uploadForm form表单数据
* @param fileDataName 文件对应的字段名称
* @return
* @throws IOException
*/
public static InputStream getByteArrayInputStream(Map<String, List<InputPart>> uploadForm, String fileDataName) throws IOException {
InputStream inputStream = getInputStreamFromBody(uploadForm, fileDataName);
byte[] bytes = IOUtils.toByteArray(inputStream);
inputStream = new ByteArrayInputStream(bytes);
return inputStream;
}
}
分类:
其他--dubbo
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· DeepSeek 开源周回顾「GitHub 热点速览」
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
2018-04-24 操作系统基础知识
2018-04-24 计算机原理思考