【发布时间】:2018-04-09 17:29:49
【问题描述】:
我正在开发 Spring hibernate 项目,我想将文件上传到服务器目录。如果我将文件保存到手动指定的目录,则文件成功上传到指定的路径。但我想要一条路径,这样当我将项目上传到云端时,我不需要做任何更改。
我尝试了“user.dir”,但它为我提供了安装 STS 的路径。但我不想要这条路。
我的控制器附在下面
public class FileUploadController {
@Autowired
private FileUploadDAO fileUploadDao;
@RequestMapping(value = "/uploadFile", method = RequestMethod.POST)
public void handleFileUpload(HttpServletRequest request,
@RequestParam CommonsMultipartFile[] fileUpload/*,@PathVariable("student_id") long student_id*/) throws Exception {
if (fileUpload != null && fileUpload.length > 0) {
for (CommonsMultipartFile aFile : fileUpload){
String orginalName=aFile.getOriginalFilename();
System.out.println("Saving file: " + orginalName);
File currentDirFile = new File(".");
String helper = currentDirFile.getAbsolutePath();
helper = helper.substring(0, helper.length()-1);
System.out.println("helper : "+helper);
String path= request.getServletContext().getInitParameter(helper);
System.out.println("path : "+path);
String path1=request.getServletContext().getContextPath();
String finalPath=path1+File.separator+"src"+File.separator+"main"+File.separator+"webapp"+File.separator+"img"+File.separator;
String f1=helper+finalPath;
System.out.println("f1 : "+f1);
File file = new File(finalPath);
System.out.println(path);
System.out.println(path1);
System.out.println("finalPath : "+finalPath);
if (!file.exists()) {
if (file.mkdir()) {
System.out.println("Directory is created!");
String filePath = finalPath+"/"+orginalName;
File destination = new File(filePath);
// fileUploadDao.savePath(filePath);
String status ="success";
try {
aFile.transferTo(destination);
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
status="failure";
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
status="iofailure";
}
System.out.println(filePath);
fileUploadDao.save(filePath);
}
else {
System.out.println("Failed to create directory!");
}
}else{
System.out.println("Directory is already exist!");
String filePath = finalPath+orginalName;
System.out.println("filePath : "+filePath);
File destination = new File(f1);
String status ="success";
try {
aFile.transferTo(destination);
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
status="failure";
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
status="iofailure";
}
System.out.println(filePath);
fileUploadDao.save(filePath);
// }
}
}
//return "Success";
}
【问题讨论】:
-
那么你想保存当前用户目录下的所有文件吗?正确
-
是的..但是当前目录(使用 (user.dir) 或仅 (.))向我显示 STS 安装目录。我什至尝试保存到我的 webapp 中的 img 目录,但它给出了找不到路径的异常
-
如果我检查 img 目录的路径,它会显示相同的 STS 路径
-
您使用的服务器是什么?部署 。原因是它走上了服务器的道路。您能在 STS 安装文件夹中确认服务器吗
-
我正在使用 apache tomcat。我没明白你所说的“你能确认 STS 安装文件夹中的服务器”是什么意思吗?请详细说明
标签: hibernate spring-mvc