java rpc学习之rest 学习之Resteasy 文件上传(10)

前提
后端服务使用Jboss restEasy搭建rest服务
业务需求需要使用文件上传功能
文件上传格式为浏览器表单上传文件
实现步骤
1.添加依赖
reasteasy解析表单文件需要添加扩展依赖,以maven项目为例,依赖如下:

<dependencies>
    <!--resteasy 基础依赖-->
    <dependency>
        <groupId>org.jboss.resteasy</groupId>
        <artifactId>resteasy-jaxrs</artifactId>
        <version>3.1.0.Final</version>
    </dependency>

    <!--reasteasy multipart 表单扩展依赖-->
    <dependency>
        <groupId>org.jboss.resteasy</groupId>
        <artifactId>resteasy-multipart-provider</artifactId>
        <version>3.0.0.Final</version>
    </dependency>

</dependencies>

2.编写接口
resteasy解析表单数据需要使用org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataInput接口,下面代码示例说明接口编写方式

/**
 * 获取解析上传的文件
 *
 * @param multipartFormDataInput
 * @return
 * @throws Exception
 */
@POST
@Path("/upload")
@Consumes(MediaType.MULTIPART_FORM_DATA)//接收数据类型为MULTIPART_FORM_DATA
@Produces(MediaType.APPLICATION_JSON)
public Boolean uploadStockAnalyseScriptFile(MultipartFormDataInput multipartFormDataInput)
        throws Exception {
    //获取表单中的数据map
    Map<String, List<InputPart>> dataMaps = multipartFormDataInput.getFormDataMap();

    //根据表单元素名称获取表单元素(需要同前端同学沟通好表单元素的name)
    List<InputPart> fileParts = dataMaps.get("file");//表单元素-文件

    //解析获取表单文件的输入流
    InputStream inputStream;
    try {
        if (fileParts == null || fileParts.isEmpty())
            throw new Exception("请求参数为空!");

        InputPart filePart = fileParts.get(0);
        inputStream = filePart.getBody(InputStream.class, null);
    } catch (Exception e) {
        throw new Exception(e.getMessage());
    }

    //保存文件至本地
    String filePathName = "C:\\Users\\Johnson\\Desktop\\newFile.txt";
    File target = new File(filePathName);
    FileOutputStream fos = null;
    try {
        if (!target.getParentFile().exists())
            target.getParentFile().mkdirs();
        fos = new FileOutputStream(target);
        byte[] b = new byte[1024];
        int readLength;
        while ((readLength = inputStream.read(b)) != -1) {
            fos.write(b, 0, readLength);
        }
    } catch (Exception e) {
        throw new AssistanceException(e.getMessage());
    } finally {
        if (inputStream != null)
            inputStream.close();
        if (fos != null)
            fos.close();
    }

    return true;
}

另外,解析表单文件元素文件名,解析表单元素获取字串的方式如下
import org.jboss.resteasy.plugins.providers.multipart.InputPart;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
/**
 * 从表单文件元素中提取文件名
 * 
 * @param filePart
 * @return
 * @throws Exception
 */
public static String getFileNameByFileInputPart(InputPart filePart) throws Exception {
    String[] contentDispositionHeader = filePart.getHeaders().getFirst("Content-Disposition").split(";");
    for (String fileName : contentDispositionHeader) {
        if ((fileName.trim().startsWith("filename"))) {
            String[] tmp = fileName.split("=");
            String fileNameStr = tmp[1].trim().replaceAll("\"", "");
            return fileNameStr;
        }
    }
    return null;
}

/**
 * 从表单元素中获取字串文本并以UTF-8编码
   * 
 * @param inputPart
 * @return
 * @throws Exception
 */
public static String getInputPartAsString(InputPart inputPart) throws Exception {
    if (inputPart == null)
        return null;
    String nameString = inputPart.getBodyAsString();
    if (nameString == null || nameString.isEmpty())
        return null;
    return URLDecoder.decode(nameString, StandardCharsets.UTF_8.name());
}
 

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值