Dropwizard文件上传 [英] Dropwizard file upload
本文介绍了Dropwizard文件上传的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我必须从我的网站上载一个文件,但cnt似乎无法使用拖放向导来工作。
I have to upload a file from my site yet cnt seem to get it working with drop wizard.
这是我网站上的表格。
<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>
我将如何在后端接收文件?
How would I go about on the backend to receive the file?
解决方案是
@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
Also, if you're using 0.7.0-rc2, you will need this dependency in your pom.xml
<dependency>
<groupId>com.sun.jersey.contribs</groupId>
<artifactId>jersey-multipart</artifactId>
<version>1.18</version>
</dependency>
这篇关于Dropwizard文件上传的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文