以下是关于Java中使用Jersey实现文件上传的两种方法的详细攻略:
1. 使用FormDataMultiPart方式上传文件
实现步骤
- 添加Jersey依赖
在pom.xml中添加以下依赖:
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-multipart</artifactId>
<version>2.33</version>
</dependency>
- 实现POST接口
在控制器中实现POST接口,在其中通过FormDataMultiPart类处理文件上传,将上传的文件保存到指定路径。
@Path("/fileUploader")
public class FileUploader {
@POST
@Path("/uploadFile")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFile(FormDataMultiPart form) throws IOException {
FormDataBodyPart filePart = form.getField("file");
ContentDisposition contentDisposition = filePart.getContentDisposition();
String fileName = contentDisposition.getFileName();
InputStream fileInputStream = filePart.getValueAs(InputStream.class);
File targetFile = new File("/fileDirectory" + fileName);
Files.copy(fileInputStream, targetFile.toPath());
return Response.ok("File uploaded successfully.").build();
}
}
示例
以下示例代码实现了使用FormDataMultiPart方式上传文件:
public class FileUploadTest {
public static void main(String[] args) {
File file = new File("test.jpg");
FormDataMultiPart form = new FormDataMultiPart();
form.bodyPart(new FileDataBodyPart("file", file, MediaType.APPLICATION_OCTET_STREAM_TYPE));
Client client = ClientBuilder.newClient();
WebTarget target = client.target("http://localhost:8080/fileUploader/uploadFile");
Response response = target.request().post(Entity.entity(form, MediaType.MULTIPART_FORM_DATA));
System.out.println(response.getStatus());
response.close();
}
}
2. 使用InputStream方式上传文件
实现步骤
- 实现POST接口
在控制器中实现POST接口,在其中通过InputStream类处理文件上传,将上传的文件保存到指定路径。
@Path("/fileUploader")
public class FileUploader {
@POST
@Path("/uploadFile")
@Consumes(MediaType.APPLICATION_OCTET_STREAM)
public Response uploadFile(InputStream fileInputStream, @HeaderParam("Content-Disposition") String contentDisposition) throws IOException {
String fileName = contentDisposition.replaceFirst("(?i)^.*filename=\"?([^\"]+)\"?.*$", "$1");
File targetFile = new File("/fileDirectory" + fileName);
Files.copy(fileInputStream, targetFile.toPath());
return Response.ok("File uploaded successfully.").build();
}
}
示例
以下示例代码实现了使用InputStream方式上传文件:
public class FileUploadTest {
public static void main(String[] args) throws FileNotFoundException {
File file = new File("test.jpg");
String uploadUrl = "http://localhost:8080/fileUploader/uploadFile";
Client client = ClientBuilder.newClient();
WebTarget target = client.target(uploadUrl);
InputStream inputStream = new FileInputStream(file);
FormDataContentDisposition contentDisposition = FormDataContentDisposition.name("file").fileName(file.getName()).build();
Response response = target.request(MediaType.APPLICATION_OCTET_STREAM)
.header(HttpHeaders.CONTENT_DISPOSITION, contentDisposition)
.post(Entity.entity(inputStream, MediaType.APPLICATION_OCTET_STREAM_TYPE));
System.out.println(response.getStatus());
response.close();
}
}
希望以上内容对您有所帮助。
本站文章如无特殊说明,均为本站原创,如若转载,请注明出处:基于Java中两种jersey文件上传方式 - Python技术站