1. 程式人生 > >js實現檔案的上傳和直接預覽(不經過服務端)

js實現檔案的上傳和直接預覽(不經過服務端)

js實現檔案的上傳,注意要使用BASE64編碼!
<div  class="bottom-border mt10">
						<input type="hidden" id="imgcodeBusiness" value=""/>
						<input type="hidden" id="imgUrlBusiness" value=""/>
			            <h5 class="color1 font-weight-normal" style="width:50%;"></h5>上傳圖片
			            </div>
			            <div id="imguploadBusiness" style="overflow-y:auto;">
							 <div class="addImg" id="addImgBusiness"></div>
							 <div class="addF" style="margin-top:10px;">
			                    <input accept="image/*" type="file" class="addFm" id="upLoadBusiness"/>
			                 </div>
							<!--  <input accept="image/*" type="file" class="addFm" id="upLoadBusiness"/> -->
						</div> 

js程式碼

$("#upLoadBusiness", parent.document).unbind("change").bind("change",(function(e) {
					var imgcode = $("#imgcodeBusiness", parent.document).val();
					var that = this.files[0];
					var type = ((that.type).split('/'))[1];
					controller.run(this, function(data) {
						var img = new Image(), div = document.createElement('div');
						img.style.width = '100px';
						img.style.height = '100px';
						div.appendChild(img);
						parent.document.getElementById("addImgBusiness",parent.document).appendChild(div);
						img.src = data;
						img.onclick = function() {
							window.open(data);
						}
						cpic.ajax("task/taskUploadImg" + "?t="+ new Date().getTime(), {
							type : type,
							base64 : data,
							imgcode : imgcode
						}, function(data) {
							if(data.returnUrl!=null && data.returnUrl!=undefined && data.returnUrl!=""){
								$("#imgUrlBusiness", parent.document).val(data.returnUrl);
							}
						}, function() {
						});
					});

				}));
this.run = function(input_file, get_data) {
			/* input_file:檔案按鈕物件 */
			/* get_data: 轉換成功後執行的方法 */
			if (typeof (FileReader) === 'undefined') {
				alert("抱歉,你的瀏覽器不支援 FileReader,不能將圖片轉換為Base64,請使用現代瀏覽器操作!");
			} else {
				try {
					/* 圖片轉Base64 核心程式碼 */
					var file = input_file.files[0];
					// 這裡我們判斷下型別如果不是圖片就返回 去掉就可以上傳任意檔案
					if (!/image\/\w+/.test(file.type)) {
						alert("請確保檔案為影象型別");
						return false;
					}
					var reader = new FileReader();
					reader.onload = function() {
						get_data(this.result);
					}
					reader.readAsDataURL(file);
				} catch (e) {
					alert('圖片轉Base64出錯啦!' + e.toString())
				}
			}
		};
後臺程式碼
/**
	 * 上傳圖片
	 * 
	 * @param requestBody
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "taskUploadImg", produces = "application/json")
	@ResponseBody
	public Map<String, Object> taskUploadImg(
			@RequestBody Map<String, Object> requestBody) throws Exception {
		Map<String, Object> resultMap = new HashMap<String, Object>();

		String base64 = (String) requestBody.get("base64");
		String downimgcode = (String) requestBody.get("imgcode");
		String type = (String) requestBody.get("type");
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		String formatDate = sdf.format(new Date());
		if (downimgcode != "" && downimgcode != null) {
			type = type.substring(type.indexOf(".") + 1);
			CodeEntryEO codeEntryEO = dataCacheManager.getCodeEntryCacheByName(
					"image", "uploadPath");
			String uploadPathStr = "";
			if (codeEntryEO != null) {
				uploadPathStr = codeEntryEO.getExtendType();
			}
			if (!uploadPathStr.endsWith("/")) {
				uploadPathStr = uploadPathStr + "/";
			}
			String uploadPath = uploadPathStr + "uploadFile/business_img/"
					+ formatDate + "/" + downimgcode + "/";
			// 檢查上傳檔案的目錄
			File uploadDir = new File(uploadPath);
			// deleteFile(uploadDir);
			if (!uploadDir.exists()) {// 判斷資料夾是否建立,沒有建立則建立新資料夾
				uploadDir.mkdirs();
			}
			// 新檔名
			String newname = DateUtil.DateTimeNumber() + "." + type;
			resultMap.put("herf", uploadPath + newname);
			Base64Decoder decoder = new Base64Decoder();
			File imageFile = new File(uploadPath, newname);
			// 建立輸出流
			FileOutputStream outputStream = new FileOutputStream(imageFile);
			try {

				// 獲得一個圖片檔案流,我這裡是從flex中傳過來的
				byte[] img = decoder.decode(base64.split(",")[1]);// 解碼
				for (int i = 0; i < img.length; ++i) {
					if (img[i] < 0) {// 調整異常資料
						img[i] += 256;
					}
				}
				outputStream.write(img);
			} catch (Exception e) {
			} finally {
				if (outputStream != null) {
					outputStream.close();
				}
			}
			resultMap.put("returnUrl", uploadPath);
		}

		return resultMap;
	}