最近正在写有关文件操作的程序,搞得我也是焦头烂额。业务很简单:前台用户需要选择一个jar包然后上传到服务器(localhost)然后由后台的Java程序进行指定目录的存储,然后将文件路径转存到mongodb中。
但是,前台的代码始终没有成功的实现,传统的form表单提交和比较友好的ajaxSubmit都没有成功,目前原因还在排查当中。
我今天暂时先把后台文件存储的大致逻辑写了出来,在这里记录一下。
/**
* 文件上传
*
* @param file
* @return
*/
@RequestMapping(value = "/uploadjarpackage")
public String uploadJarPackage(String thingsParseId, @RequestParam("file") MultipartFile file,
HttpServletRequest request) {
if (thingsParseId != null) {// 编辑物解析
} else {// 新增物解析
if (!file.isEmpty()) {
try {
File temp = new File("");
BufferedOutputStream out = new BufferedOutputStream(
new FileOutputStream(new File(temp.getAbsolutePath() + "\\" + file.getOriginalFilename())));
out.write(file.getBytes());
out.flush();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
return "上传失败!" + e.getMessage();
} catch (IOException e) {
e.printStackTrace();
return "上传失败!" + e.getMessage();
}
return "上传成功!";
} else {
return "上传失败,文件是空的!";
}
}
return "";
}
后台程序用的是spring系的框架(springboot),temp的作用是通过getAbsolutePath()方法获得项目的根路径,这段代码我在另一个main方法中做了个“代码原型测试”,“原型代码”如下所示:
public static void main(String[] args) throws IOException {
File oldFile = new File("C:\\Users\\mht\\Desktop\\json.jar");
File newFile = new File("");
String rootPath = newFile.getAbsolutePath();
File yesFile = new File(rootPath + "\\" + oldFile.getName());
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(yesFile));
System.out.println("文件名:" + oldFile.getName());// output:文件名:json.jar
System.out.println("保存后的文件路径:" + yesFile.getAbsolutePath());
// output:保存后的文件路径:D:\workspace\crc-16\json.jar
FileInputStream fis = new FileInputStream(oldFile);
ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
byte[] b = new byte[1000];
int n;
while ((n = fis.read(b)) != -1) {
bos.write(b, 0, n);
}
fis.close();
bos.close();
byte[] fileBytes = bos.toByteArray();
out.write(fileBytes);
out.close();
}
上述代码的作用是将桌面上的一个json.jar文件转存到了项目的根路径下。
主要思路就是:通过输出流BufferedOutputStream将 文件对象的bytes数组write到指定路径下,最后关闭流。但是File类的实例并没有getBytes()的行为方法,因此在原型代码中做了一个小小的转化,其目的无非也就是获得byte数组。
第二段代码,应该是文件存储的传统思路,可能会有更好的方法,比如用哪一种流比较好等等。
另外,关于文件的相关操作,我希望可以慢慢整理出来。