天天看點

input file 多檔案上傳 Java

input file 多檔案上傳 Java

    • html
    • js
    • java

html

<input readonly="readonly" onclick="img(1);" id="imagesUpload" name="imagesUpload" />
	<button onclick="startUpload(1);" type="button" >開始上傳</button>
	<input readonly="readonly" onclick="img(1);" id="videosUpload" name="videosUpload" />
	<button onclick="startUpload(2);" type="button" >開始上傳</button>
	<input readonly="readonly" onclick="img(1);" id="othersUpload" name="othersUpload" />
	<button onclick="startUpload(3);" type="button" >開始上傳</button>
	<form id="fileForm" action="" target="uploadIFrame" method="POST" enctype="multipart/form-data">
			<input type="file" id="filesUpload" name="file" onchange="filePath();" multiple="multiple">
	</form>
           

js

var uploadType = "";
//檔案上傳
function img(type){
	uploadType = type;
	$("#filesUpload").click();
}

//所選檔案路徑
function filePath(){
	var path = $("#filesUpload").val();
	var domfile=document.getElementById("filesUpload").files;
	var nameStr="";
	for(var x=0;x<domfile.length;x++){//檔案名
		nameStr += domfile[x].name+",";
	}
	if (uploadType == "1") {//檔案名傳回至input标簽
		$("#imagesUpload").val(nameStr.substring(0,nameStr.length-1));
	} else if (uploadType == "2") {
		$("#videosUpload").val(nameStr.substring(0,nameStr.length-1));
	} else {
		$("#othersUpload").val(nameStr.substring(0,nameStr.length-1));
	}
}

//開始上傳
function startUpload(type){
	var form = new FormData(document.getElementById("fileForm"));
	form.append("fileType",uploadType);//類型 1-圖檔,2-視訊,3-其他附件
	var fileInput = '';
	if (type == "1") {
		fileInput = $("#image").val();
	} else if (type == "2") {
		fileInput = $("#video").val();
	} else {
		fileInput = $("#accessory").val();
	}

	if (fileInput == "") {
		alert("請先選擇再開始上傳!");
	} else {
	var actionUrl="";//ajax送出路徑
	$.ajax({
				type : 'POST',
				url : actionUrl,
				dataType : 'json',
				data:form,
		        processData:false,
		        contentType:false,
				success : function(data) {
					if (data.status == 0) { // 上傳成功
						if (type == "1") { //data.url為儲存路徑	/files/imgs/20190329170020763060.png
							$("#imagesUpload").val(data.url);
						} else if (type == "2") {
							$("#filesUpload").val(data.url);
						} else {
							$("#othersUpload").val(data.url);
						}
						alert(data.msg);					
					} else {
						alert(data.msg);					
					}
				}
			});
		}
           

java

/**
	 * 檔案上傳
	 * @param request
	 * @param response
	 * @param fileType 檔案類型;1-圖檔,2-視訊,3-其他
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "/uploadFiles", method = { RequestMethod.GET, RequestMethod.POST })
	@ResponseBody
	public Map<String, Object> uploadFile(HttpServletRequest request,HttpServletResponse response, String fileType) {
		MultipartHttpServletRequest muRequest = (MultipartHttpServletRequest) request;
		List<MultipartFile> files = muRequest.getFiles("file");
		Map<String, Object> map = new HashMap<String, Object>();
		String filePath = ""; // 傳回位址
		int countSuccess=0;
		for (MultipartFile file : files) {
			// 檔案大小MB
			float fileSize = (float) file.getSize() / 1024 / 1024;
			// 列印上傳的檔案時多少MB
			System.out.println("檔案大小:"+fileSize / 1024 / 1024 + "MB");
			String ext = FilenameUtils.getExtension(file.getOriginalFilename()); // 檔案的擴充名

			// 判斷檔案大小
			if (judgeFileSize(fileType, fileSize)) {
				// 判斷檔案格式
				if (judgeFileSuffix(fileType, ext)) {
					//時間格式    命名檔案名
					DateFormat df = new SimpleDateFormat("yyyyMMddHHmmssSSS");
					// 檔案名稱
					String name = df.format(new Date());
					Random r = new Random();
					for (int i = 0; i < 3; i++) {
						name += r.nextInt(10);
					}
					// 檔案名 20190329170020763060.png
					String fileName = name + "." + ext;
					try {
						// 目前WEB環境的上層目錄	E:\apache-tomcat-8.0.53\webapps
						String webParentPath = new File(request.getServletContext().getRealPath("/")).getParent().replace("\\", "/");
						
						String realPath = ""; // 檔案上傳到伺服器的真實路徑
						if ("1".equals(fileType)) {	//E:/apache-tomcat-8.0.53/webapps/files/imgs
							realPath = webParentPath + File.separator + "files" + File.separator + "imgs" ;
						} else if ("2".equals(fileType)) {
							realPath = webParentPath + File.separator + "files" + File.separator + "videos";
						} else {
							realPath = webParentPath + File.separator + "files" + File.separator + "others";
						}
						
						// 建立檔案夾
						File up = new File(realPath);
						if (!up.exists()) {//如不存在則建立
							up.mkdirs();
						}
						//file ----》  ( realPath +  File.separator + fileName )
										//E:/apache-tomcat-8.0.53/webapps/files/imgs/20190329170020763060.png
						file.transferTo(new File(realPath +  File.separator + fileName)); // 檔案上傳 
						
						if ("1".equals(fileType)) {//傳回給頁面路徑以備儲存至資料庫
							filePath += "/files" + "/imgs/" + fileName+",,";
						} else if ("2".equals(fileType)) {
							filePath += "/files" + "/videos/" + fileName+",,";
						} else {
							filePath += "/files" + "/others/" +  fileName+",,";
						}
						//成功+1
						countSuccess++;
					} catch (Exception e) {
						map.put("status", 1);
						map.put("msg", "上傳失敗!");
						System.err.println("上傳失敗!");
					}
				} else {
					if ("1".equals(fileType)) { // 檔案類型;1-圖檔,2-視訊,3-其他
						map.put("status", 1);
						map.put("msg", "圖檔格式不正确!");
					} else if ("2".equals(fileType)) {
						map.put("status", 1);
						map.put("msg", "視訊隻能是mp4格式!");
					}
				}
	
			} else {
				if ("1".equals(fileType)) { // 檔案類型;1-圖檔,2-視訊,3-其他
					if (fileSize > 5) { // 圖檔不能大于5M
						map.put("status", 1);
						map.put("msg", "圖檔不能大于5M!");
					} 
				} else if ("2".equals(fileType)) {
					if (fileSize > 300) { // 視訊不能大于500M
						map.put("status", 1);
						map.put("msg", "視訊不能大于300M!");
					} 
				} else {
					if (fileSize > 500) { // 其他類型檔案不能大于500M
						map.put("status", 1);
						map.put("msg", "檔案不能大于500M!");
					} 
				}
			}
		}
		if(countSuccess==files.size()){
			map.put("status", 0);
			map.put("msg", "上傳成功!");
			map.put("url", filePath.substring(0,filePath.length()-2));
		}
		return map;
	}

	/**
	 * 判斷檔案不同類型的擴充名
	 * @param fileType 檔案類型
	 * @param ext 擴充名(例如:mp4,jpg)
	 * @return
	 */
	private boolean judgeFileSuffix(String fileType, String ext) {
		String imgs = "bmp,jpg,png,tif,gif,pcx,tga,exif,fpx,svg,psd,cdr,pcd,dxf,ufo,eps,ai,raw,WMF,webp";
		String videos = "mp4";
		if ("1".equals(fileType)) { // 檔案類型;1-圖檔,2-視訊,3-其他
			if (imgs.indexOf(ext) > -1)  {
				return true;
			} 
		} else if ("2".equals(fileType)) {
			if (videos.indexOf(ext) > -1)  {
				return true;
			} 
		} else {
			return true;
		}
		return false;
	}

	/**
	 * 判斷檔案不同類型時的大小
	 * @param fileType 檔案類型
	 * @param fileSize 檔案大小(機關M)
	 * @return 類型與大小不符傳回false
	 */
	private boolean judgeFileSize(String fileType, float fileSize) {
		if ("1".equals(fileType)) { // 檔案類型;1-圖檔,2-視訊,3-其他
			if (fileSize > 5) { // 圖檔不能大于5M
				return false;
			} 
		} else if ("2".equals(fileType)) {
			if (fileSize > 300) { // 視訊不能大于500M
				return false;
			} 
		} else {
			if (fileSize > 500) { // 其他類型檔案不能大于500M
				return false;
			} 
		}
		return true;
	}