1. 程式人生 > >使用FormData物件ajax非同步方式上傳圖片,檔案

使用FormData物件ajax非同步方式上傳圖片,檔案

HTML程式碼

<div id="uploadForm">
    <input id="file" type="file"/>
    <button id="upload" type="button">upload</button>
</div>

這裡沒有<form>標籤,也沒有enctype="multipart/form-data"屬性。

javascript程式碼

var formData = new FormData();
formData.append('myfile', $('#file')[0].files[0]);
$.ajax({
    url: '請求路徑/uploadPic
'
, type: 'POST', cache: false, data: formData, processData: false, contentType: false }).done(function(res) { }).fail(function(res) {});

這裡有幾處不一樣:

  • append()的第二個引數應是檔案物件,即$('#file')[0].files[0]
  • contentType也要設定為‘false’。

從程式碼$('#file')[0].files[0]中可以看到一個<input type="file">標籤能夠上傳多個檔案,
只需要在<input type="file">

裡新增multiplemultiple="multiple"屬性。


java程式碼

@RequestMapping(value = "/uploadPic",produces = "application/json")
@ResponseBody
	public Object importPicFile(String picParams, MultipartFile myfile, HttpServletRequest request,HttpServletResponse response)
			throws IOException {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		Map<String, Object> map = new HashMap<String, Object>();
		if (myfile.isEmpty()) {
			map.put("result", "error");
			map.put("msg", "上傳檔案不能為空");
			return String. valueOf(JSONObject.fromObject (resultMap));
		} else {
			String originalFilename = myfile.getOriginalFilename();
			// String fileBaseName=FilenameUtils.getBaseName(originalFilename);
			String dirName = "image";
			// 定義允許上傳的副檔名
			HashMap<String, String> extMap = new HashMap<String, String>();
			extMap.put("image", "gif,jpg,jpeg,png,bmp");
			// 檢查副檔名
			String fileExt = originalFilename.substring(originalFilename.lastIndexOf(".") + 1).toLowerCase();
			if (!Arrays.<String>asList(extMap.get(dirName).split(",")).contains(fileExt)) {
				resultMap.put( "result", "error");  
				resultMap.put( "msg", "上傳副檔名是不允許的副檔名。\n只允許" + extMap.get(dirName) + "格式。" );
				return String. valueOf(JSONObject.fromObject (resultMap));
				//return Results.byMessage(ShowTextUtils.FAIL, "上傳副檔名是不允許的副檔名。\n只允許" + extMap.get(dirName) + "格式。");
			}
			// 設定目錄
			if (IConstants.ISDEMO.equals("1")) {
				dirName = "demo/file/sys/" + dirName + "/" + new SimpleDateFormat("yyyy/yyyyMMdd").format(new Date());
			} else {
				dirName = "file/sys/" + dirName + "/" + new SimpleDateFormat("yyyy/yyyyMMdd").format(new Date()) + "/";
			}
	
			// 檔案儲存目錄路徑
			String savePath = getFilePath() + dirName;
			// 新檔名
			String newFileName = getFileName() + "." + fileExt;
			
			 // 檢查目錄
			File uploadDir = new File(savePath);
			if (!uploadDir.isDirectory()) {
				uploadDir.mkdirs();
			}
			// 檢查目錄寫許可權
			if (!uploadDir.canWrite()) {
				resultMap.put( "result", "error");  
				resultMap.put( "msg", "上傳目錄沒有寫許可權。");
				return String. valueOf(JSONObject.fromObject (resultMap));
			}
			
			try {
				// 把上傳的圖片放到伺服器的資料夾下
				FileUtils.copyInputStreamToFile(myfile.getInputStream(), new File(savePath, newFileName));

			} catch (Exception e) {
				resultMap.put( "result", "error");  
				resultMap.put( "msg", e.getMessage() );
				return String. valueOf(JSONObject.fromObject (resultMap));
				//return Results.byMessage(ShowTextUtils.FAIL, e.getMessage());
			}
			// 上傳檔案
			File uploadedFile = new File(savePath, newFileName);
			// 上傳阿里雲(沒有這個需求可以註釋掉)
			upyun = new UpYun(BUCKET_NAME, OPERATOR_NAME, OPERATOR_PWD);
			upyun.setDebug(false);

			// 要傳到upyun後的檔案路徑
			String filePath = "/" + dirName + "/" + getFileName() + "." + fileExt;

			// 設定待上傳檔案的 Content-MD5 值
			// 如果又拍雲服務端收到的檔案MD5值與使用者設定的不一致,將回報 406 NotAcceptable 錯誤
			upyun.setContentMD5(UpYun.md5(uploadedFile));

			// 上傳檔案,並自動建立父級目錄(最多10級)
			boolean result = upyun.writeFile(filePath, uploadedFile, true);

			if (result) {
				filePath = URL + filePath;
			}
			resultMap.put( "result", "success");  
			resultMap.put( "msg", "上傳圖片成功" );
			resultMap.put( "filePath", filePath );
			return String. valueOf(JSONObject.fromObject (resultMap));
			}
	}
	public String getFilePath() {
		String os = System.getProperty("os.name");
		if (os.toLowerCase().startsWith("win")) {
			// 正式環境Web所在目錄
			return "F:/soft/image/webapps/ROOT/";
		} else {
			// 正式環境 linux 目錄 /opt/tomcat-instance/web/webapps/ROOT/ +
			// “WEB-INF/outHtml/***.jsp”
			return "/opt/tomcat-instance/dx_manager/ROOT/";
		}

	}

	public String getFileName() {
		SimpleDateFormat simpledateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
		Random random = new Random();
		return simpledateFormat.format(new Date()) + random.nextInt(10000);
	}