项目使用myeclipe写的。
源码在D:\Workspaces\MyEclipse 10\frame目录下,项目名为frame。
现在文件上传功能实现了 将文件上传至tomcat服务器上运行的webapp目录下的file文件夹下,例如D:\Program Files\apache-tomcat-7.0.96\webapps\frame\file\a.txt 为本地上传a.txt成功后的路径。现在要求将文件上传至D:\Workspaces\MyEclipse 10\frame\WebRoot\file目录下,以后将项目在公司服务器上运行,就是上传文件至服务器源码文件夹下,路径不能写死,请问要如何实现?
以下为上传功能主要的源码:
String Path =request.getSession().getServletContext().getRealPath("");
String basePath =Path+ "\\file";
// 如果文件目录不存在,就执行创建
File targetFile = new File(basePath);
if (!targetFile.isDirectory()) {
targetFile.mkdirs();
}
// 拼接目标文件
File outfile = new File(basePath+ File.separator + file.getOriginalFilename());
// 获取本地文件输入流
InputStream stream = file.getInputStream();
// 声明服务器要存储的目标文件输出流
FileOutputStream fos = new FileOutputStream(outfile);
// 写入目标文件
byte[] buffer = new byte[1024 * 1024];
int byteRead = 0;
while ((byteRead = stream.read(buffer)) != -1) {
fos.write(buffer, 0, byteRead);
// 把缓冲区的内容强制的写出,避免关闭流时丢失数据
fos.flush();
}
// 关闭流
fos.close();
stream.close();