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

发布于 2025-01-31 20:06:31 字数 1198 浏览 1 评论 0原文

我正在用Groovy脚本编写一个REST API,该API将从客户端接收文件上传。 REST API将通过HttpservletRequest接收文件。 我试图通过获取其输入流来从httpservletrequest获取文件,然后将其转换为文件以保存到适当的文件夹。 我的代码如下:

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

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

I am writing a REST API in Groovy script that will receive a file upload from client side.
The REST API will receive the file via HttpServletRequest.
I am trying to get the file from HttpServletRequest by getting its InputStream, then convert it to File to save to proper folder.
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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

剧终人散尽 2025-02-07 20:06:31

找到了使用多植物的解决方案

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();

Found the solution with 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();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文