我正在用Groovy脚本编写一个REST API,它将接收从客户端上传的文件。REST API将通过HttpServletRequest接收文件。我试图通过获取文件的InputStream从HttpServletRequest获取文件,然后将其转换为File并保存到适当的文件夹中。我的代码如下:
RestApiResponse doHandle(HttpServletRequest request, RestApiResponseBuilder apiResponseBuilder, RestAPIContext context) {
InputStream inputStream = request.getInputStream()
def file = new File(tempFolder + "//" + fileName)
FileOutputStream outputStream = null
try
{
outputStream = new FileOutputStream(file, false)
int read;
byte[] bytes = new byte[DEFAULT_BUFFER_SIZE];
while ((read = inputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, read);
}
}
finally {
if (outputStream != null) {
outputStream.close();
}
}
inputStream.close();
// the rest of the code
}
文件已创建,但它们都已损坏。当我尝试用记事本打开它们时,它们都有,在开始时,类似于下面的一些东西:
-----------------------------134303111730200325402357640857
Content-Disposition: form-data; name="pbUpload1"; filename="Book1.xlsx"
Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
我做错了吗?我如何正确地获取文件?
1条答案
按热度按时间pcww981p1#
使用MultipartStream找到解决方案