需求是這樣的,先上傳文件,因為只傳文件沒有辦法生成一級目錄文件夾,傳過來參數又不好取,所以就先上傳,然后后面提交的時候移動文件到新的目錄:
public static String moveFile(String name, String path, String number) throws IOException { //移動文件夾 File fromPath = new File(path + File.separator + name);
//這個url不要new File,否則outStream的地方報錯,拼出來的路徑是:D:/resources/uploads/123/abc.png String url = path + File.separator + number + File.separator + name; FileChannel in = null; FileChannel out = null; FileInputStream inStream = null; FileOutputStream outStream = null; try { inStream = new FileInputStream(fromPath); File toPath = new File(path + File.separator + number); System.out.println("fileUrl: " + toPath); if (!toPath.exists()) { toPath.mkdirs(); } outStream = new FileOutputStream(url); in = inStream.getChannel(); out = outStream.getChannel(); IOUtils.copy(inStream, outStream); } catch (IOException e) { e.printStackTrace(); } finally { inStream.close(); in.close(); outStream.close(); out.close(); //刪除原來文件,必須等流關閉后才能刪除 fromPath.deleteOnExit(); }
//這是存入數庫的路徑 String imagePath = "/uploads/" + number + "/"+ name; return imagePath; }