Java中上傳文件到代碼中和刪除代碼中的文件


1.上傳文件到指定的項目地址中

     @ResponseBody // 返回json數據
	@ApiOperation(value = "圖片上傳生成地址")
	@RequestMapping(value = "/testUploadimg", method = RequestMethod.POST)
	public String uploadImg(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
		String path = "";
		String contentType = file.getContentType();
		String fileName = file.getOriginalFilename();
		// 自動獲取項目的根路徑
		String filePath = request.getSession().getServletContext().getRealPath("/") + "img/";//這塊可以填寫相應的位置
		// String filePath = "";
		if (file.isEmpty()) {
			return "文件為空!";
		}
		try {
			// 把文件保存到項目中
			path = uploadFile(file.getBytes(), filePath, fileName);
		} catch (Exception e) {
			// TODO: handle exception
		}
		// 返回json
		return path;
	}

	public String uploadFile(byte[] file, String filePath, String fileName) throws Exception {
		String path = "";
		File targetFile = new File(filePath);
		if (!targetFile.exists()) {
			targetFile.mkdirs();
		}
		FileOutputStream out = new FileOutputStream(filePath + "/" + fileName);
		path = filePath + "/" + fileName;
		out.write(file);
		out.flush();
		out.close();
		return path;
	}

  2.在項目中刪除指定文件和文件夾

    public boolean fileTest(String path) {
		// 刪除文件
		String strVectorFile = path;
		boolean bo = deleteFile(strVectorFile);
		// 刪除文件夾
		String strVectorDir = "D:\\test2";
		deleteDirectory(strVectorDir);
		return bo;
	}

	public static boolean deleteFile(String fileName) {
		File file = new File(fileName);
		if (file.isFile() && file.exists()) {
			Boolean succeedDelete = file.delete();
			if (succeedDelete) {
				System.out.println("刪除單個文件" + fileName + "成功!");
				return true;
			} else {
				System.out.println("刪除單個文件" + fileName + "失敗!");
				return true;
			}
		} else {
			System.out.println("刪除單個文件" + fileName + "失敗!");
			return false;
		}
	}

	public static boolean deleteDirectory(String dir) {
		// 如果dir不以文件分隔符結尾,自動添加文件分隔符
		if (!dir.endsWith(File.separator)) {
			dir = dir + File.separator;
		}
		File dirFile = new File(dir);
		// 如果dir對應的文件不存在,或者不是一個目錄,則退出
		if (!dirFile.exists() || !dirFile.isDirectory()) {
			System.out.println("刪除目錄失敗" + dir + "目錄不存在!");
			return false;
		}
		boolean flag = true;
		// 刪除文件夾下的所有文件(包括子目錄)
		File[] files = dirFile.listFiles();
		for (int i = 0; i < files.length; i++) {
			// 刪除子文件
			if (files[i].isFile()) {
				flag = deleteFile(files[i].getAbsolutePath());
				if (!flag) {
					break;
				}
			}
			// 刪除子目錄
			else {
				flag = deleteDirectory(files[i].getAbsolutePath());
				if (!flag) {
					break;
				}
			}
		}

		if (!flag) {
			System.out.println("刪除目錄失敗");
			return false;
		}

		// 刪除當前目錄
		if (dirFile.delete()) {
			System.out.println("刪除目錄" + dir + "成功!");
			return true;
		} else {
			System.out.println("刪除目錄" + dir + "失敗!");
			return false;
		}
	}

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM