我必须从我的网站上传一个文件,但 cnt 似乎可以使其与放置向导一起使用。
这是我网站上的表格。
<form enctype="multipart/form-data" method="POST" action="UploadFile">
<input type="file" id="fileUpload" name="file"/>
<input type="hidden" id="fileName" name="fileName"/>
<input type="submit" value="Upload"/>
</form>
我将如何在后端接收文件?
解决方案是
@POST
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFile(
@FormDataParam("file") final InputStream fileInputStream,
@FormDataParam("file") final FormDataContentDisposition contentDispositionHeader) {
String filePath = uploadLocation + newFileName;
saveFile(fileInputStream, filePath);
String output = "File can be downloaded from the following 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();
}
}
您可以使用 nio 以更少的行数将内容保存到服务器
java.nio.file.Path outputPath = FileSystems.getDefault().getPath(<upload-folder-on-server>, fileName);
Files.copy(fileInputStream, outputPath);
另外,如果您使用 0.7.0-rc2,您的 pom.xml 中将需要此依赖项
<dependency>
<groupId>com.sun.jersey.contribs</groupId>
<artifactId>jersey-multipart</artifactId>
<version>1.18</version>
</dependency>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)