1. 程式人生 > >Java中利用MultipartFile實現檔案上傳

Java中利用MultipartFile實現檔案上傳

JavaWeb專案頁面實現檔案上傳功能

jsp檔案增加檔案上傳控制元件,可以放在form表單內,增加隱藏域儲存上傳路徑提交到後臺。

<div class="form-group">
					<div class="col-sm-7 center ">
				        <input class="btn btn-xs btn-primary" type="button"  id="uploadBtn" value="選擇上傳檔案">
					   	<input type="file" class="hidden"  name="file" id="fileupload" onchange="">
			    		<input id="apkUrl" name="apkUrl" value="">
			    		<label id="fileName"></label>
				    <div class="hidden" id="uploadimg">
				    <img alt="uploading..." src="${ctx}/static/images/upload.gif">正在上傳,請稍後...</div>
		        </div>

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);
        }  		
  	}