Java中利用MultipartFile实现文件上传

JavaWeb项目页面实现文件上传功能

jsp文件增加文件上传控件,可以放在form表单内,增加隐藏域保存上传路径提交到后台。


js方法:

$("#fileupload").fileupload({
	   	acceptFileTypes: /(\.|\/)(apk)$/i,
	   	url:'${ctx}/layout/apk/uploadFile',
	    dataType: 'json',
	    add:function(e,data){
	    	var fileName = data.files[0].name;
	    	var exurl=fileName.substring(fileName.lastIndexOf('.')+1,fileName.length);
			if(exurl!= 'apk'){
				$('#fileName').text("不是apk文件,请重新上传!");
			}else{ 
	        	data.context=$('#fileName').text("");
	       		$('#uploadimg').removeClass('hidden');
	       		data.submit();
			} 
	    },
	    success: function (data) {
	    	$("#apkUrl").val(url + data.msg);
			$('#uploadimg').addClass('hidden');
			$("#fileName").html("上传成功");		
		},  
	}); 

Java后台controller方法:

@RequestMapping(value = "/uploadFile" , method = RequestMethod.POST)
  	public void uploadApk(HttpServletRequest request, HttpServletResponse response,@RequestParam(value = "file") MultipartFile file,
  				Model model){
  		String path = request.getSession().getServletContext().getRealPath("upload");
        String fileName = file.getOriginalFilename();
        File targetFile = new File(path, fileName);  
        if(!targetFile.exists()){  
            targetFile.mkdirs();  
        }  
   
        try {
            file.transferTo(targetFile);
            if(path != null && !path.equals("")){
            	String newPath = path.replaceAll("\\\\", "/");
                JsonResult data = new JsonResult();
                data.setMsg(newPath);
    			Renders.renderJson(response,data);
        	}else{
        		Renders.renderJson(response, Renders.SAVE_FAILURE);
        	}  
        } catch (Exception e) {  
            e.printStackTrace();
            Renders.renderJson(response, Renders.SAVE_FAILURE);
        }  		
  	}







你可能感兴趣的:(web前端)