上傳文件

1、jsp中注意問題

//文件上傳,注意form中要定義  enctype="multipart/form-data"

<form action="<%=basePath%>system/appversion/save.do" method="post" 
	 id="form-appversion-edit-add" enctype="multipart/form-data" >
	<div>
		<label >文件:</label>
		<input type="file" name="apkFile"  id="apkFile"><button type="button" id="uploadButton" onclick="uploadApk()">上傳</button>
	</div>
	<div >
		<label >文件路徑:</label>
		<input type="text" class="input-text" value="${pd.appUrl }" name="appUrl" id="appUrl_edit" datatype="*" nullmsg="請選擇文件" readonly="readonly">
	</div>
	
	<div>		
		<input id="appEdit_submitButton" class="btn btn-primary radius" type="submit" value="&nbsp;&nbsp;提交&nbsp;&nbsp;">
	</div>	
</form>

②js中ajax中提交文件

<script type="text/javascript">
	//上傳文件,這裏是封裝到form數據中傳給後臺。不是form的submit提交。
	function uploadApk(){
		var apkFile = $("#apkFile").val();
		if(apkFile == ''){
			layer.alert("請選擇文件");
			return;
		}
		var formData = new FormData($("#apkFile")[0].files[0]);
		formData.append("apkFile",$("#apkFile")[0].files[0]);
		$.ajax({
			type:'POST',
			url:'system/appversion/upload.do',
			data:formData,
			dataType:"json",
			processData : false, 
			contentType : false,
			success: function(data){
				$("#appUrl_edit").val(data.appUrl);
				$("#uploadButton").attr("disabled", true); 
			},
			error: function(err){
				layer.alert("服務器錯誤");
			}
		});
	}

</script>


③後臺上傳的方法

	/**
	 *app版本管理上傳文件
	 * 
	 * @param
	 * @throws Exception
	 */
	@ActionDesc(description="app版本管理上傳文件",methodType="post")
	@RequestMapping(value = "/upload")
	@ResponseBody
	public AppVersion upload(@RequestParam(required = false)MultipartFile apkFile) throws Exception {
		String appUrl = "";
		if (!apkFile.isEmpty()) {
			// 文件原名稱
			String fileName = apkFile.getOriginalFilename();
			String formatDay = DateUtil.getDays();
			// 爲了避免重複簡單處理
			String photoImagePath = PropertyUtil.readValue(Const.APK_PATH);
			long currentTimeMillis = System.currentTimeMillis();
			// 上傳位置路徑
			String path0 = photoImagePath + "/" + formatDay + "/" + currentTimeMillis + "/" + fileName;
			// 按照路徑新建文件
			File newFile = new File(path0);
			File newFile1 = new File(photoImagePath + "/" + formatDay + "/" + currentTimeMillis);
			if (!newFile1.exists()) {
				newFile1.mkdirs();
			}
			// 複製
			FileCopyUtils.copy(apkFile.getBytes(), newFile);
			appUrl = "appversion/downloadNewApk.do?newApkUrl=" + path0;
		}
		AppVersion appVersion = new AppVersion();
		appVersion.setAppUrl(appUrl);
		return appVersion;
	}


④後臺下載方法

只要不是在項目中,即在其他目錄下,那麼就需要通過流的方式去讀取文件,返回一個流。

/**
	 * 下載apk
	 * 
	 * @param newApkUrl
	 *            最新的apk下載的URL
	 * 
	 */
	@ActionDesc(description = "下載apk", methodType = "post")
	@RequestMapping("/downloadNewApk")
	@ResponseBody
	public void downloadNewApk(String newApkUrl) throws Exception {
		HttpServletResponse response = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
				.getResponse();// 獲取response
		if (!Tools.isEmpty(newApkUrl)) {
			// 文件路徑(windows下是\\,linux下是//,都必須是絕對路徑)
			String path = PropertyUtil.readValue(Const.APK_PATH) + newApkUrl;
			// java中用File類來表示一個文件
			java.io.File newFile = new java.io.File(path);
			// 測試這個文件路徑是否存在(也就是這個文件是否存在)
			if (!newFile.exists()) {
				return;
			}
			// FileUtils.readFileToByteArray(File file)把一個文件轉換成字節數組返回
			byte[] data = FileUtils.readFileToByteArray(newFile);
			String[] strArr = newApkUrl.split("/");
			String fileName = strArr[strArr.length - 1];
			response.reset();
			// 設置文件的返回類型
			response.setContentType("application/octet-stream;charset=UTF-8");
			response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
			response.addHeader("Content-Length", "" + data.length);
			OutputStream outputStream = response.getOutputStream();
			outputStream.write(data);
			// java在使用流時,都會有一個緩衝區,按一種它認爲比較高效的方法來發數據:
			// 把要發的數據先放到緩衝區,緩衝區放滿以後再一次性發過去,而不是分開一次一次地發.
			// 而flush()表示強制將緩衝區中的數據發送出去,不必等到緩衝區滿.
			outputStream.flush();
			outputStream.close();
		} else {
			return;
		}
	}








發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章