简体   繁体   English

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

[英]In Groovy, how to properly get the file from HttpServletRequest

I am writing a REST API in Groovy script that will receive a file upload from client side.我正在用 Groovy 脚本编写一个 REST API,它将接收来自客户端的文件上传。 The REST API will receive the file via HttpServletRequest. REST API 将通过 HttpServletRequest 接收文件。 I am trying to get the file from HttpServletRequest by getting its InputStream, then convert it to File to save to proper folder.我试图通过获取其 InputStream 从 HttpServletRequest 获取文件,然后将其转换为 File 以保存到正确的文件夹。 My code is as below:我的代码如下:

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
}

The files are created, but all of them are corrupted.文件已创建,但所有文件均已损坏。 When I try to open them with Notepad, all of them have, at the beginning, some thing similar to the below:当我尝试用记事本打开它们时,它们一开始都有类似下面的东西:

-----------------------------134303111730200325402357640857
Content-Disposition: form-data; name="pbUpload1"; filename="Book1.xlsx"
Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet

Am I doing this wrong?我做错了吗? How do I get the file correctly?如何正确获取文件?

Found the solution with MultipartStream使用 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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM