溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

基于SpringMVC的文件下載實例

發(fā)布時間:2020-06-24 19:57:57 來源:網(wǎng)絡 閱讀:12397 作者:pangfc 欄目:開發(fā)技術

文件的下載和文件的上傳一樣都是Web應用中一個重要的功能點。這篇“SpingMVC的文件下載”是基于以前寫過的那篇“SpringMVC實現(xiàn)文件上傳”寫的,因此這里就不從頭開始搭建測試項目了,直接接著上次的那個項目來進行測試,因此看這篇文章之前需要簡單瀏覽下上次的那篇文章

注:SpringMVC實現(xiàn)文件上傳:http://www.zifangsky.cn/406.html

(1)在UploadController.java這個controller里的upload方法中添加返回上傳之后的文件的文件名:

modelAndView.addObject("picName", targetFileName);

添加之后,這個方法的完整代碼如下:

	@RequestMapping(value = "/upload", method = RequestMethod.POST)
	public ModelAndView upload(User user, @RequestParam("file") MultipartFile tmpFile, HttpServletRequest request) {
		ModelAndView modelAndView = new ModelAndView("fileupload");

		if (tmpFile != null) {
			// 獲取物理路徑
			String targetDirectory = request.getSession().getServletContext().getRealPath("/uploads");
			String tmpFileName = tmpFile.getOriginalFilename(); // 上傳的文件名
			int dot = tmpFileName.lastIndexOf('.');
			String ext = ""; // 文件后綴名
			if ((dot > -1) && (dot < (tmpFileName.length() - 1))) {
				ext = tmpFileName.substring(dot + 1);
			}
			// 其他文件格式不處理
			if ("png".equalsIgnoreCase(ext) || "jpg".equalsIgnoreCase(ext) || "gif".equalsIgnoreCase(ext)) {
				// 重命名上傳的文件名
				String targetFileName = StringUtile.renameFileName(tmpFileName);
				// 保存的新文件
				File target = new File(targetDirectory, targetFileName);

				try {
					// 保存文件
					FileUtils.copyInputStreamToFile(tmpFile.getInputStream(), target);
				} catch (IOException e) {
					e.printStackTrace();
				}

				User u = new User();
				u.setUserName(user.getUserName());
				u.setLogoSrc(request.getContextPath() + "/uploads/" + targetFileName);

				modelAndView.addObject("u", u);
				modelAndView.addObject("picName", targetFileName);
			}

			return modelAndView;
		}

		return modelAndView;
	}

(2)在fileupload.jsp這個文件中添加一個文件下載的超鏈接:

<h3>頭像下載</h3>		
	<a href="download.html?fileName=${picName}">點擊下載</a>

可以看出,這里的fileName就是用的controller中的“picName”來賦值的

基于SpringMVC的文件下載實例

注:代碼添加的位置如上圖所示

(3)在UploadController.java中添加一個用于下載文件的方法,代碼如下:

	@RequestMapping(value = "/download", method = { RequestMethod.GET, RequestMethod.POST })
	public ResponseEntity<byte[]> download(@RequestParam(name = "fileName") String fileName,
			HttpServletRequest request) {
		HttpHeaders headers = new HttpHeaders();
		Pattern pattern = Pattern.compile("\\w*\\.\\w+");
		Matcher matcher = pattern.matcher(fileName);
		
		//檢查文件名中非法字符,只允許是字母、數(shù)字和下劃線
		if (matcher.matches()) {
			try {
				headers.setContentDispositionFormData("myfile", fileName);
				headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
				// 獲取物理路徑
				String filePath = request.getSession().getServletContext().getRealPath("/uploads");
				File pic = new File(filePath, fileName);
				return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(pic), headers, HttpStatus.CREATED);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		
		return null;
	}

注:從上面的代碼可以看出,通過接收表示文件名的字符串然后跟文件的路徑拼接起來,形成文件在磁盤中真實路徑的File對象,最后返回文件的流并進行下載。需要注意的是,為了防止出現(xiàn)任意文件下載,導致下載到其他路徑中的文件,因此在下載之前校驗了文件名的格式。同時最后返回了一個ResponseEntity<byte[]>類型的數(shù)據(jù),是為了在返回數(shù)據(jù)流的同時返回我們自定義的HttpHeaders和HttpStatus

(4)最后下載的效果如下:

基于SpringMVC的文件下載實例

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內容。

AI