天天看點

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();
		        }
		      }
		    }
		  }
		}
	    
           

繼續閱讀