Java 如何在服务器端获取实际上传的文件?
我在JAX-RS中使用RESTAPI 我刚刚上传了文件,我的服务器代码如下:Java 如何在服务器端获取实际上传的文件?,java,rest,jersey,jax-rs,multipartform-data,Java,Rest,Jersey,Jax Rs,Multipartform Data,我在JAX-RS中使用RESTAPI 我刚刚上传了文件,我的服务器代码如下: @POST @Consumes(MediaType.MULTIPART_FORM_DATA) @Produces(MediaType.TEXT_PLAIN) @Path("/upload") public String uploadFunction(@Context UriInfo uriInfo, @FormDataParam("upload") final InputStream inputStre
@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.TEXT_PLAIN)
@Path("/upload")
public String uploadFunction(@Context UriInfo uriInfo,
@FormDataParam("upload") final InputStream inputStream,
@FormDataParam("upload") final FormDataContentDisposition fileDetail) {
//Here I want to get the actual file. For eg: If i upload a myFile.txt. I need to get it as myFile.txt here
}
当我使用inputStream解析文件内容并执行某些操作时,我的代码工作正常。现在我要确切的文件。因为我需要发送附有实际文件的邮件
这里我想得到实际的文件。例如:如果我上传一个myFile.txt。我需要在这里以myFile.txt的形式获取它。如何实现它?这里我可能错了,但是当使用InputStream时,您只能获得InputStream,因为文件尚未存储在服务器上 因此,在这种情况下,您应该能够执行以下操作:
private static final String SERVER_UPLOAD_LOCATION_FOLDER = "/somepath/tmp/uploaded_files/";
@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces(MediaType.TEXT_PLAIN)
@Path("/upload")
public String uploadFunction(@Context UriInfo uriInfo,
@FormDataParam("upload") final InputStream inputStream,
@FormDataParam("upload") final FormDataContentDisposition fileDetail) {
String filePath = SERVER_UPLOAD_LOCATION_FOLDER + fileDetail.getFileName();
// save the file to the server
saveFile(inputStream, filePath);
String output = "File saved to server location : " + filePath;
return Response.status(200).entity(output).build();
}
private void saveFile(InputStream uploadedInputStream, String serverLocation) {
try {
OutputStream outputStream = new FileOutputStream(new File(serverLocation));
int read = 0;
byte[] bytes = new byte[1024];
outputStream = new FileOutputStream(new File(serverLocation));
while ((read = uploadedInputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, read);
}
outputStream.flush();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
为什么要分配两次参数
upload
。请看我更新的问题,你有输入流,你可以检索文件名。除了这个,你还需要什么?不仅仅是文件名。我想要实际的文件。因为在一些操作之后,我需要发送带有实际文件附件的邮件。