在Groovy中,如何正确地从HttpServletRequest获取文件

2q5ifsrm  于 2022-11-01  发布在  其他
关注(0)|答案(1)|浏览(270)

我正在用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

我做错了吗?我如何正确地获取文件?

pcww981p

pcww981p1#

使用MultipartStream找到解决方案

import org.apache.commons.fileupload.MultipartStream
import org.apache.commons.io.FileUtils

InputStream inputStream = request.getInputStream()
//file << inputStream;  
String fileName = "";
final String CD = "Content-Disposition: "
MultipartStream multipartStream =  new MultipartStream(inputStream, boundary);

//Block below line because it always return false for some reason
// but should be used as stated in document
//boolean nextPart = multipartStream.skipPreamble();

//Block below line as in my case, the part I need is at the first part
// or maybe I should use it and break after successfully get the file name
//while(nextPart) {
String[] headers = multipartStream.readHeaders().split("\\r\\n")
ContentDisposition cd = null
for (String h in headers) {
    if (h.startsWith(CD)) {
        cd = new ContentDisposition(h.substring(CD.length()));
        fileName = cd.getParameter("filename");         }
}             
def file = new File(tempFolder + "//" + fileName)
ByteArrayOutputStream output = new ByteArrayOutputStream(1024)
try
{
    multipartStream.readBodyData(output)
    FileUtils.writeByteArrayToFile(file, output.toByteArray());
}
finally {
    if (output != null) {
        output.flush();
        output.close(); 
    }
}
inputStream.close();

相关问题