我在我的应用程序中编写了 AJAX 文件上传功能。从我的笔记本电脑运行它时它工作得很好。当我使用相同的应用程序尝试完全相同的文件,但部署在 jBoss 服务器上时,出现以下异常:
2013-02-18 11:30:02,796 ERROR [STDERR] java.io.FileNotFoundException: C:\Users\MyUser\Desktop\TestFile.pdf (The system cannot find the file specified).
获取文件数据方法:
private byte[] getFileData(File file) {
FileInputStream fileInputStream = null;
byte[] bytFileData = null;
try {
fileInputStream = new FileInputStream(file);
} catch (FileNotFoundException e1) {
e1.printStackTrace();
}
if (fileInputStream != null) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byte[] bytBuffer = new byte[1024];
try {
for (int readNum; (readNum = fileInputStream.read(bytBuffer)) != -1;) {
byteArrayOutputStream.write(bytBuffer, 0, readNum);
}
} catch (IOException e) {
e.printStackTrace();
}
bytFileData = byteArrayOutputStream.toByteArray();
}
return bytFileData;
}
获取变量中的文件内容(通过上面的方法):
byte[] bytFileData = this.getFileData(file);
制作文件:
private boolean makeFile(File folderToMake, File fileToMake, byte[] bytFileData) {
Boolean booSuccess = false;
FileOutputStream fileOutputStream = null;
try {
if (!folderToMake.exists()) {
folderToMake.mkdirs();
}
if (!fileToMake.exists()) {
if (fileToMake.createNewFile() == true) {
booSuccess = true;
fileOutputStream = new FileOutputStream(fileToMake);
fileOutputStream.write(bytFileData);
fileOutputStream.flush();
fileOutputStream.close();
}
}
} catch (Exception e) {
e.printStackTrace();
booSuccess = false;
}
return booSuccess;
}
有什么想法吗?
谢谢
查尔斯
最佳答案
看来您只是将文件路径作为请求的一部分传递给服务器,而不是实际上传文件,然后尝试使用该文件路径访问该文件。
这将在您的笔记本电脑上运行,因为代码在本地运行时可以访问您的文件系统并且能够找到该文件。它无法部署在服务器上,因为它是完全独立的计算机,因此无法访问您的文件系统。
您需要修改客户端 (AJAX) 代码才能实际上传文件,然后修改服务器端代码以使用该上传的文件。请注意,AJAX 文件上传通常是不可能的 - 有一些框架插件(例如 jQuery)可以使用解决方法提供此功能。
我不是 100%,但我认为使用 HTML5 功能可以实现正确的 AJAX 文件上传,但目前浏览器对此的支持可能会很差。
关于从 JSP 上传文件时出现 java.io.FileNotFoundException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14941129/