问题描述
我在将文件写入系统中 tomcat 服务器的本地主机时遇到问题.
I got a problem in writing the file to the localhost of the tomcat server in my system.
如何在下面提到的位置写入文件??我收到了在提到的位置上传的文件的响应.但我不知道它存储在我系统中的什么位置.这是正确的做法吗?
How can i write file in the location mentioned Below ?? I am getting a response as the file uploaded in the location mentioned. But i don't know where it is stored in my system.. Is it the right way of doing ??
@POST
@Path("/upload")
@Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFile(
@FormDataParam("file") InputStream uploadedInputStream,
@FormDataParam("file") FormDataContentDisposition fileDetail) {
String uploadedFileLocation = "http://127.0.0.1:8080/Attachments"
+ fileDetail.getFileName();
// save it
writeToFile(uploadedInputStream, uploadedFileLocation);
String output = "File uploaded to : " + uploadedFileLocation;
return Response.status(200).entity(output).build();
}
private void writeToFile(InputStream uploadedInputStream, String uploadedFileLocation) {
try {
OutputStream out = new FileOutputStream(new File( uploadedFileLocation));
int read = 0;
byte[] bytes = new byte[1024];
out = new FileOutputStream(new File(uploadedFileLocation));
while ((read = uploadedInputStream.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
out.flush();
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
实际上我从 得到了这个 [writeToFile] 代码http://www.mkyong.com/webservices/jax-rs/file-upload-example-in-jersey/
推荐答案
您正在尝试写入名为 http://127.0.0.1:8080/Attachments/something 的
.那肯定行不通;根据 JavaDoc:File
.else
You're trying to write to a File
called http://127.0.0.1:8080/Attachments/something.else
. That is surely not going to work; according to the JavaDoc:
如果文件存在但是是一个目录而不是一个普通文件,不存在但不能创建,或者由于任何其他原因不能打开,则抛出一个 FileNotFoundException
.
由于您只是打印出异常堆栈跟踪,但没有处理失败,因此您不会收到写入文件失败的指示.检查您的服务器日志,会有一个堆栈跟踪说明找不到您尝试访问的文件.
Since you just print out your Exception stacktrace, but don't handle the failure, you don't get an indication that writing the file failed. Check your server log, there'll be a stacktrace stating the file you're trying to access cannot be found.
相反,生成一个文件名,例如 System.getProperty("java.io.tmpdir") + fileDetail.getFileName()
,然后写入该文件.File
类的 JavaDoc 声明:
Instead, generate a filename, for example System.getProperty("java.io.tmpdir") + fileDetail.getFileName()
, and write to that file. The JavaDoc for the File
class states:
在 UNIX 系统上,此属性的默认值通常是/tmp"或/var/tmp";在 Microsoft Windows 系统上,它通常是C:\WINNT\TEMP".
这篇关于Java Jersey - 如何在我的 Tomcat 服务器中写入文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!