五合一网站建设,网站备案变更主体,百度推广官网入口,网站建设与管理赚钱吗最近正在写有关文件操作的程序#xff0c;搞得我也是焦头烂额。业务很简单#xff1a;前台用户需要选择一个jar包然后上传到服务器#xff08;localhost#xff09;然后由后台的Java程序进行指定目录的存储#xff0c;然后将文件路径转存到mongodb中。
但是#xff0c;前…最近正在写有关文件操作的程序搞得我也是焦头烂额。业务很简单前台用户需要选择一个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系的框架springboottemp的作用是通过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.jarSystem.out.println(保存后的文件路径 yesFile.getAbsolutePath());// output:保存后的文件路径D:\workspace\crc-16\json.jarFileInputStream 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数组。
第二段代码应该是文件存储的传统思路可能会有更好的方法比如用哪一种流比较好等等。
另外关于文件的相关操作我希望可以慢慢整理出来。