SpringBoot項目上傳、下載文件

項目中遇到,記錄一下。

上傳文件

HTML頁面
<div class="file-loading">
	<input id="test_file" type="file" class="file-loading" accept="image/*,.pdf,.xlsx,.xls,.docx,.doc" name="file">
</div>
JS

這裏用的是bootStrap fileinput組件

$("#test_file").fileinput({
        uploadUrl: "../isv/agasdhdgjdfghdh",//"/file-upload-single/1",//上傳的地址
        language:'zh',//設置語言,中文
        dropZoneTitle: '可以將文件拖放到這裏 …不支持多文件上傳',
        allowedFileExtensions: ['jpg','png','xlsx','pdf','xls','doc','docx'],//接收的文件後綴
        showUpload: false, //是否顯示上傳按鈕
        showRemove: true, //顯示移除按鈕
        showPreview: true, //是否顯示預覽
        dropZoneEnabled: true,//是否顯示拖拽區域,
        showCaption: true,//是否顯示文件標題,默認爲true
        uploadAsync: true, //默認異步上傳
        browseClass: "btn btn-primary", //文件選擇器/瀏覽按鈕的CSS類。默認爲btn btn-primary
        minFileCount: 1, //每次上傳允許的最少文件數。如果設置爲0,則表示文件數是可選的。默認爲0
        maxFileCount: 1, //每次上傳允許的最大文件數。如果設置爲0,則表示允許的文件數是無限制的。默認爲0
        previewFileIcon: "<i class='fa fa-file-text'></i>",//當檢測到用於預覽的不可讀文件類型時,將在每個預覽文件縮略圖中顯示的圖標。默認爲<i class="glyphicon glyphicon-file"></i>  
        msgInvalidFileExtension: "不正確的文件擴展名 {name}. 只支持 {extensions}的文件擴展名.",
        enctype: 'multipart/form-data',
	}).on("filebatchselected", function(e, files) {        
        $(this).fileinput("upload");             // 文件選擇完直接調用上傳方法。
    });
Controller
System.getProperty(“user.dir”);參數即可獲得項目相對路徑。(ps:不知道是不是springboot內嵌tomcat容器的原因,用網上的request.getServletContext().getRealPath("/")方法獲得的路徑不是項目路徑,而是c盤下一個tomcat目錄路徑)
	@RequestMapping("/saveFile")
	@ResponseBody
	public JSONObject saveFile(@RequestParam("file") MultipartFile file) {
		//獲取文件名
		String fileName = file.getOriginalFilename();
		//文件後綴名
		String subffix = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
		//文件保存進來,我給他重新命名,數據庫保存有原本的名字,所以輸出的時候再把他附上原本的名字就行了。
		String newFileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
		//獲取項目絕對路徑
		String filePath = System.getProperty("user.dir")+"\\src\\main\\resources\\templates\\files";
		File newFile = new File(filePath);
		//保存文件
		file.transferTo(new File(newFile+"\\"+newFileName+"."+subffix));
        //保存路徑
		String realpath = newFile+"\\"+newFileName+"."+subffix;
        //返回路徑
		josn = getJsonResult(true, realpath ,StateParameter.SUCCESSFUL_MSG);
			
		return josn;
	}
	

下載文件

HTML頁面
用 bootStrap-Table 加的表格按鈕,按鈕綁觸發事件,沒有HTML代碼	
JS
window.operateEvents={
		"click #file_list_tab_down_load":function (e, value, row, index) {//下載
			//參數可以在from裏拼input標籤,設置隱藏提交from的時候傳參數
			//這裏傳的是文件信息在數據庫裏的id,方便下載
			var $eleForm = $("<form method='post'><input name='fileId' id='file_id' value="+row.id+" style='display: none;'></form>");
			//請求路徑
			$eleForm.attr("action","http://localhost:8080/isv/downFile");
			//body裏添加進去這個from
			$(document.body).append($eleForm);
			//提交表單,實現下載
			$eleForm.submit();
		}
		
	}
Controller
	/**
	 * 下載附件
	 * @param res
	 * @param id
	 */
	@RequestMapping( value = "/downFile")
	@ResponseBody
	public void downFile(HttpServletResponse res,@RequestParam(name = "fileId") Integer id ) {
		//參數列表裏 RequestParam的name屬性要和from中拼接的input裏的name要一樣,不然接不到參數
		//文件詳細信息,路徑,文件名,改完之後的文件名等等
		FileObject fileObject = iRepairOrderService.getOneFileObject(id);
		for(int x=0;x<2;x++) {
			res.setHeader("content-type", "application/octet-stream");
			res.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");  
			try {
				//解決中文文件名亂碼,不然文件名會變成下劃線
				res.setHeader("Content-Disposition", String.format("attachment; filename=\"%s\"",URLEncoder.encode(fileObject.getFileName(), "utf-8") ));
			} catch (UnsupportedEncodingException e1) {
				System.err.println(e1.getMessage());
				e1.printStackTrace();
			}  
			res.setHeader("Pragma", "no-cache");  
			res.setHeader("Expires", "0");  
		    res.setContentType("application/octet-stream;charset=utf-8");
		    byte[] buff = new byte[1024];
		    BufferedInputStream bis = null;
		    OutputStream os = null;
		    try {
		      os = res.getOutputStream();
		      //文件在項目中的絕對路徑
		      bis = new BufferedInputStream(new FileInputStream( 
		                new File(System.getProperty("user.dir")+"\\src\\main\\resources\\templates\\files\\" + fileObject.getNewFileName())));
		      int i = bis.read(buff);
		 
		      while (i != -1) {
		        os.write(buff, 0, buff.length);
		        os.flush();
		        i = bis.read(buff);
		      }
		    } catch ( IOException e ) {
		      e.printStackTrace();
		    } finally {
		      if (bis != null) {
		        try {
		          bis.close();
		        } catch (IOException e) {
		          e.printStackTrace();
		        }
		      }
		    }
		  }
		}
	    
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章