我正在尝试将客户端提供的文件复制到临时文件中。
这个给定的文件由我的 REST 服务检索到 InputStream 中。
这是我的代码:
@POST
@Path("fileupload")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFile(
@FormDataParam("uploadFormElement") InputStream uploadedInputStream,
@FormDataParam("uploadFormElement") FormDataContentDisposition fileDetail)
throws IOException {
Response.Status respStatus = Response.Status.OK;
if (fileDetail == null) {
respStatus = Response.Status.INTERNAL_SERVER_ERROR;
} else {
if (uploadedInputStream != null) {
try {
initPath();
int size = 0;
int bytesRead;
boolean isStreamSizeCorrect = true;
byte[] buffer = new byte[1024];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while ((bytesRead = uploadedInputStream.read(buffer)) != -1) {
if (size > OntoWebStudioUtil.getUploadFileLimit()) {
isStreamSizeCorrect = false;
baos.close();
while ((bytesRead = uploadedInputStream.read(buffer)) != -1) {
size++;
}
break;
} else {
baos.write(buffer, 0, bytesRead);
}
size++;
}
if (!isStreamSizeCorrect) {
respStatus = Response.Status.NOT_ACCEPTABLE;
return Response
.status(respStatus)
.entity("Size of uploaded file exceeds the limit"
+ OWSConstants.UPLOAD_RESPONSE_VALUE_SEPARATOR
+ size).build();
}
byte[] outBuf = baos.toByteArray();
String newFilePath = "C:\\Docs\\my_pic.png";
FileOutputStream fos = null;
try {
fos = new FileOutputStream(newFilePath);
fos.write(outBuf);
}
catch (IOException e) {
e.printStackTrace(System.err);
}
finally {
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
} catch (Exception e) {
respStatus = Response.Status.INTERNAL_SERVER_ERROR;
e.printStackTrace(System.out);
}
}
}
return Response
.status(respStatus)
.entity(tempFileName
+ OWSConstants.UPLOAD_RESPONSE_VALUE_SEPARATOR
+ currentFileName).build();
}
}
我遇到的问题是在我的临时目录中创建的文件是空的。 我必须在创建文件之前测试文件的大小。这就是我阅读 InputStream 的原因。所以我在阅读过程中试图复制一份它。但这不起作用。我能做什么?
谢谢
最佳答案
如果您使用的是 Java SE 7 或更高版本,则可以使用 Files.copy .
关于java - 从输入流创建文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23111811/