我尝试使用Jersey multipart进行上传。一切运作良好。但我无法上传文件名。我认为这是图书馆的问题。
这是我的pom.xml
的依赖项<dependencies>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.bundles</groupId>
<artifactId>jaxrs-ri</artifactId>
<version>2.21</version>
</dependency>
<dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.3</version>
</dependency>
<dependency>
<groupId>org.glassfish.jersey.media</groupId>
<artifactId>jersey-media-multipart</artifactId>
<version>2.17</version>
</dependency>
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-core</artifactId>
<version>1.18.1</version>
</dependency>
</dependencies>
我的UpploadFileService
@Path("/file")
public class UploadFileService {
@POST
@Path("/upload")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFile(
@FormDataParam("file") InputStream uploadedInputStream,
@FormDataParam("file1") FormDataContentDisposition fileDetail) {
...
}
}
如果我将@FormDataParam("file1")
更改为@FormDataParam("file")
,POST请求将返回Bad Request
。但没有它,它运作良好。
我怎样才能获得文件名?为什么@FormDataParam("file")
使服务返回Bad Request?
我上传的HTML
<html>
<body>
<h1>File Upload with Jersey</h1>
<form action="http://localhost:8080/Project/api/file/upload" method="post" enctype="multipart/form-data">
<p>
Select a file : <input type="file" name="file" size="45" />
</p>
<input type="submit" value="Upload It" />
</form>
</body>
</html>
应用
@ApplicationPath("/api")
public class Application extends javax.ws.rs.core.Application {
public Set<Class<?>> getClasses() {
final Set<Class<?>> resources = new HashSet<>();
resources.add(UploadFileService.class);
resources.add(MultiPartFeature.class);
return resources;
}
}
答案 0 :(得分:1)
您可以使用String fileName = fileDetail.getFileName();
Jersey 1
使用com.sun
个包,Jersey 2
使用org.glassfish
个包。切勿混合它们。替换你的
<dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-core</artifactId>
<version>1.18.1</version>
</dependency>
有了这个:
<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-server</artifactId>
<version>2.22.1</version>
</dependency>