Java Web 学习笔记之十三:RestEasy接口处理浏览器表单上传的文件

来源:互联网 发布:21天学通java 第6版 编辑:程序博客网 时间:2024/06/09 14:04

RestEasy接口处理浏览器表单上传的文件

前提

  • 后端服务使用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());}

这两个方法可以当做工具方法来使用

阅读全文
0 0
原创粉丝点击