RestEasy上传文件的工具类

前言

RestEasy是比较老的技术,有挺多坑,非必要不建议使用。
网络上相关的资料也比较少,只能自己封装一个工具类。

RestEasy上传文件的资料,可以看一下: https://i.cnblogs.com/posts/edit;postId=14590557

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;
    }



}



原文地址:https://www.cnblogs.com/expiator/p/14698649.html