我在上传文件方面遇到了问题。当我自己上传文件(localhost)时它实际上有效但当我让同一网络中的其他人上传他们的文件时它会给我一个错误:
(The system cannot find the path specified)
at java.io.FileInputStream.open(Native Method)
at java.io.FileInputStream.<init>(FileInputStream.java:120)
at sources.UploadAIP.actions.uploadAction.processRequest(uploadAction.java:49)
这是我的实际代码:
public class uploadAction extends AbstractAppAction
{
public boolean processRequest(HttpServlet servlet, HttpServletRequest request, HttpServletResponse response)
{
try{
Properties appProperties = getAppProperties();
String dbMap = appProperties.getProperty("dbMap");
DB db = getDBConnection(dbMap);
String myDirectory = "C:\\tmp";
String uploadedFile = request.getParameter("filename");
System.out.println("srcfile: " +myDirectory);
System.out.println("file: " +uploadedFile);
String errorMessage = "";
ServletContext sc = servlet.getServletContext();
String fileName = StringUtil.stringReplace(uploadedFile,"\\","\\");
int i = fileName.lastIndexOf("\\");
if (i > 0) {
fileName = fileName.substring(i+1);
}
File srcFile = new File(uploadedFile);
File targetDirectory = new File(myDirectory);
String dirname = StringUtil.stringReplace(targetDirectory.toString() ,"\\","\\");
System.out.println("directory name:" +dirname);
File destFile = new File(dirname+"\\"+fileName);
System.out.println(destFile);
System.out.println("here is the parent directory: " +targetDirectory);
if(!targetDirectory.exists()){
targetDirectory.mkdirs();
}
InputStream inStream;
OutputStream outStream;
try{
inStream = new FileInputStream(srcFile);
outStream = new FileOutputStream(destFile);
byte[] buffer = new byte[4096];
int length;
//copy the file content in bytes
while ((length = inStream.read(buffer)) > 0){
outStream.write(buffer, 0, length);
}
outStream.close();
}catch(Exception e){
e.printStackTrace();
}
fileName = StringUtil.stringReplace(uploadedFile, "\\", "\\");
int u = fileName.lastIndexOf("\\");
if (u > 0)
{
fileName = fileName.substring(i + 1);
}
if (!dirname.endsWith("\\"))
{
dirname = dirname + "\\";
}
File f = new File(dirname);
String uploadDir = dirname;
System.out.println("uploadDirectory" +uploadDir);
} catch (Exception ex) {
request.setAttribute("message", ex.toString());
ex.printStackTrace();
}
return (true);
}
}
答案 0 :(得分:0)
您的代码假定正在上传的文件存在于同一台本地计算机上,这是不正确的,因为您正在接收来自本地网络的上传。
这就是它在本地计算机上运行的原因,但不适用于网络。
要上传文件,您需要一个多部分表单和一个正确处理多部分请求的servlet。
本教程可以帮助您:
http://www.avajava.com/tutorials/lessons/how-do-i-upload-a-file-to-a-servlet.html