我正在构建一个java RestService并尝试从前端上传一个Image并尝试将其保存在我的计算机上。问题是我只能在关闭服务器后打开上传的图像。当我在服务器仍在运行时尝试打开图像时,我只得到一个黑色图像......
这是我的代码:
private void writeToFile(InputStream uploadedInputStream,
String uploadedFileLocation) {
try {
OutputStream out = new FileOutputStream(new File(uploadedFileLocation));
int read = 0;
byte[] bytes = new byte[1024];
out = new FileOutputStream(new File(uploadedFileLocation));
while ((read = uploadedInputStream.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
这是我调用writeToFile()...
的代码 @POST
@Path("/upload")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFile(
@FormDataParam("file") InputStream uploadedInputStream,
@FormDataParam("file") FormDataContentDisposition fileDetail) {
String uploadedFileLocation = "c://Users/leona/Desktop/EOT/src/main/Backend_EOT/sparti-meetme-63dfc731c375/meetmeserver/src/main/webapp/" + name;
// save it
writeToFile(uploadedInputStream, uploadedFileLocation);
String output = "File uploaded to : " + uploadedFileLocation;
try {
uploadedInputStream.close();
}catch (Exception e) {
log.debug("Input Stream konnte nicht geschlossen werden");
}
return Response.status(200).entity(output).build();
}
如果有人可以帮助我,我真的很感激。
答案 0 :(得分:0)
This is the right way to write data to a file, from an arbitrary input stream. This ensures that the file descriptor will be flushed and closed.
private void writeToFile(InputStream uploadedInputStream, String uploadedFileLocation) {
try (OutputStream out = Files.newOutputStream
(Paths.get(uploadedFileLocation), StandardOpenOption.WRITE, StandardOpenOption.CREATE)) {
int read = 0;
byte[] bytes = new byte[8192];
while ((read = uploadedInputStream.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
答案 1 :(得分:-1)
You're opening 2 FileOutputStream
s but only closing one of them. here is a snippet of your code with a comment added by me, showing which line to delete:
try {
OutputStream out = new FileOutputStream(new File(uploadedFileLocation));
int read = 0;
byte[] bytes = new byte[1024];
// delete the following line, you already opened the output stream right after the `try`.
out = new FileOutputStream(new File(uploadedFileLocation));
As an aside, make sure you close the uploadedInputStream
. It's not being closed in the code you posted. The best practice would be to close it in the same scope you create it in, which in this case would be outside of the function you posted.
Now that we see more of the code, we see that you're being passed an InputStream
by a framework. Let the framework handle closing it. As mentioned above, the best practice is to close streams in the scope they are created in. In this case, that would be the Jersey framework.