【发布时间】:2014-03-20 06:58:06
【问题描述】:
我必须从我的网站上传一个文件,但 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();
}
}
【问题讨论】:
-
你可以回答你自己的问题你知道吗?事实上,你应该回答你自己的问题,而不是把答案放在问题中
-
为什么要分配给 outputStream 两次?
标签: dropwizard