【发布时间】:2019-09-30 06:37:29
【问题描述】:
所以我正在尝试下载我之前上传的文件,使用 rest get 方法,但有时我得到文件未找到错误,而其他时候它只是工作。不知道问题出在哪里。
我还尝试了此线程 file downloading in restful web services 中的代码并对其进行了一些更改,但此代码的问题是我看不到文件的内容,所以我认为我的解决方案要好一些。
@GET
@Path("/{fileName}")
@Produces(MediaType.APPLICATION_OCTET_STREAM)
public Response downloadFile(@PathParam("fileName") String fileName) throws IOException
{
File ivyFile = new File(fileName);
byte[] data = ivyFile.readBinary().toByteArray();
StreamingOutput fileStream = new StreamingOutput()
{
@Override
public void write(java.io.OutputStream output)
{
try
{
output.write(data);
output.flush();
}
catch (IOException e)
{
throw new WebApplicationException("Could not Find the file: '" + fileName + "'", e);
}
}
};
return Response.ok(fileStream, MediaType.APPLICATION_OCTET_STREAM)
.header("content-disposition", "attachment; filename = " + fileName).build();
}
我希望下载包含内容的文件并能够看到它。
编辑: 发生此错误时,我也会收到响应 200。还有这个错误:
MalformedChunkCodingException: CRLF expected at end of chunk
FacesException: org.apache.http.MalformedChunkCodingException: CRLF expected at end of chunk
Error during rendering of html dialog 'com.axonivy.connectivity.rest.FileUpload'
【问题讨论】:
-
你能不能直接做 output.write("Hello World") 看看能不能在下载的文件中得到它。
-
@Ganeshchaitanya 我无法将字符串放入 OutputStream
-
但是您可以 String.getBytes 并将其放入输出流中吗?
-
@Antoniossss 哦,是的,那是真的。所以当我把字符串放在 output.write 中时,它就在 File 中了。但是我不得不再次尝试下载它几次,因为它显示该文件未找到
-
试试 builder#entity(new ByteArrayEntity(yourData));因此可能会保留异常处理。/