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());
}
這兩個方法可以當做工具方法來使用