html5上传

<div id="drop_area">将图片拖拽到此区域</div>
			<div id="preview"></div>


<script type="text/javascript">
$(function(){     
	//阻止浏览器默认行。     
	$(document).on({        
		dragleave:function(e){    
			//拖离             
			e.preventDefault();         
		},         
		drop:function(e){  
			//拖后放            
			e.preventDefault();         
		},         
		dragenter:function(e){    
			//拖进             
			e.preventDefault();         
		},         
		dragover:function(e){    
			//拖来拖去             
			e.preventDefault();         
		}     
	});

	var box = document.getElementById('drop_area'); 
	//拖拽区域    
	box.addEventListener("drop",function(e){         
		e.preventDefault(); //取消默认浏览器拖拽效果         
		var fileList = e.dataTransfer.files; //获取文件对象         
		//检测是否是拖拽文件到页面的操作         
		if(fileList.length == 0){             
			return false;         
		}         
		//检测文件是不是图片         
		if(fileList[0].type.indexOf('image') === -1){            
			alert("您拖的不是图片!");             return false;         
		}                  
		//拖拉图片到浏览器,可以实现预览功能         
		var img = window.URL.createObjectURL(fileList[0]);         
		var filename = fileList[0].name; //图片名称         
		var filesize = Math.floor((fileList[0].size)/1024);          
		if(filesize>5000){             
			alert("上传大小不能超过5000K.");             
			return false;         
		}
		var str = "<img src='"+img+"'><p>图片名称:"+filename+"</p><p>大小:"+filesize+"KB</p>";         
		$("#preview").html(str);                  
      	
		var fd = new FormData();
        //关联表单数据,可以是自定义参数
		fd.append('mypic', fileList[0]); 
		//xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
		//监听事件
		xhr.upload.addEventListener("progress", uploadProgress, false);
		xhr.addEventListener("load", uploadComplete, false);
		xhr.addEventListener("error", uploadFailed, false);
		xhr.addEventListener("abort", uploadCanceled, false);
		//发送文件和表单自定义参数
		xhr.open("POST", ROOT_PATH+"builder/image/upload");
		xhr.send(fd);
		
	},false); 
	
}); 
</script>

<script type="text/javascript">
    var xhr = new XMLHttpRequest();
     
    //监听选择文件信息
    function fileSelected() {
        //HTML5文件API操作
          var file = document.getElementById('fileName').files[0];
          if (file) {
            var fileSize = 0;
            if (file.size > 1024 * 1024)
              fileSize = (Math.round(file.size * 100 / (1024 * 1024)) / 100).toString() + 'MB';
            else
              fileSize = (Math.round(file.size * 100 / 1024) / 100).toString() + 'KB';
 
            document.getElementById('fileName').innerHTML = 'Name: ' + file.name;
            document.getElementById('fileSize').innerHTML = 'Size: ' + fileSize;
            document.getElementById('fileType').innerHTML = 'Type: ' + file.type;
          }
        }
     
    //上传文件
	function uploadFile() {
		var fd = new FormData();
          //关联表单数据,可以是自定义参数
		fd.append('mypic', fileList[0]); 
		xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
		//监听事件
		xhr.upload.addEventListener("progress", uploadProgress, false);
		xhr.addEventListener("load", uploadComplete, false);
		xhr.addEventListener("error", uploadFailed, false);
		xhr.addEventListener("abort", uploadCanceled, false);
		//发送文件和表单自定义参数
		xhr.open("POST", ROOT_PATH+"builder/image/upload");
		xhr.send(fd);
	}
    //取消上传
    function cancleUploadFile(){
        xhr.abort();
    }
     
    //上传进度
	function uploadProgress(evt) {
   	if (evt.lengthComputable) {
    var percentComplete = Math.round(evt.loaded * 100 / evt.total);
        document.getElementById('progressNumber').innerHTML = percentComplete.toString() + '%';
      }
      else {
        document.getElementById('progressNumber').innerHTML = 'unable to compute';
      }
	}
 
    //上传成功响应
    function uploadComplete(evt) {
        //服务断接收完文件返回的结果
        alert(evt.target.responseText);
    }
         
    //上传失败
    function uploadFailed(evt) {
         alert("上传失败");
    }
    //取消上传
    function uploadCanceled(evt) {
        alert("您取消了本次上传.");
    }
    </script>

@RequestMapping(value = "/upload", method = RequestMethod.POST)
	@ResponseBody
	public String upload(DefaultMultipartHttpServletRequest request) throws IOException {
		MultiValueMap<String, MultipartFile> map = request.getMultiFileMap();
		List<MultipartFile> multipartFiles = (List<MultipartFile>) map
				.get("mypic");
		String path = getFileUploadPath();
        String absolutePath = getAbsolutePath(path, request);
        File folder = new File(absolutePath);
        if (!folder.exists()) {
            folder.mkdirs();
        }
		for (MultipartFile multipartFile : multipartFiles) {
			String rawName = multipartFile.getOriginalFilename();
	        String fileExt = rawName.substring(rawName.lastIndexOf("."));
	        String newName = System.currentTimeMillis() + UUID.randomUUID().toString() + fileExt;
	        File saveFile = new File(absolutePath + File.separator + newName);
	        FileOutputStream fs = new FileOutputStream(saveFile);
			SaveFileFromInputStream(multipartFile.getInputStream(), fs);
			
			Resource image = new Resource();
			image.setName(rawName);
			image.setType(resourceTypeService.findByCode(TypeCode.IMAGE));
			String attachment = getFileUploadPath()+"/"+newName;
			image.setAttachment(attachment);
			String filePath = Strings.isNullOrEmpty(attachment) ? null : getAbsolutePath(attachment, request);
			resourceService.save(image);
			filePath = Strings.isNullOrEmpty(attachment) ? null : getAbsolutePath(attachment, request);
	        resourceService.saveFile(image, filePath);
			setImageProperty(image);
			resourceService.update(image);
		}
		
		return "redirect:/builder/image";
	}

	public void SaveFileFromInputStream(InputStream stream, FileOutputStream fs) throws IOException {
		byte[] buffer = new byte[1024 * 1024];
		@SuppressWarnings("unused")
		int bytesum = 0;
		int byteread = 0;
		while ((byteread = stream.read(buffer)) != -1) {
			bytesum += byteread;
			fs.write(buffer, 0, byteread);
			fs.flush();
		}
		fs.close();
		stream.close();
	}


你可能感兴趣的:(html5上传)