multipart/form-data 上傳文件,html前臺以及Java後臺寫法

1.首先,form表單里加上enctype="multipart/form-data"

<form id="form-coursewareContent" method="post"
        enctype="multipart/form-data">

</form>

2.添加選擇文件文本框

 <div class="uploadBox">
	 	<input type="file" class="uploadContBtn" name="adjunctUpload" id="adjunctUpload"></div>  

3.頁面js

			$("#adjunctUpload").on("change",function () {
			    var formData;
				formData = new FormData($("#form-coursewareContent")[0])
			   $.ajax({
                    //url路徑自己注意寫
					 url : "/imageUpload",
					 data : formData,
					 processData : false,  //必須false纔會避開jQuery對 formdata 的默認處理   
			         contentType : false,  //必須false纔會自動加上正確的Content-Type
					 type : "post",
					 dataType : 'text',
					
					success : function(data) {
						if(data=="error"){
							alert("error")
						}else{
						var path=data;
						console.log(path)
						$("#coursewareImgurl").val(path)
						}
					}
			  });
		});

後臺:

@ResponseBody
    @RequestMapping("/imageUpload")
    public Map<String,Object> imageUpload(HttpServletRequest request, HttpServletResponse response,@RequestParam(value = "file", required = false)MultipartFile image) {
		Map<String,Object> map = new HashMap<String, Object>();
		String fileName = image.getOriginalFilename(); //獲取文件名
		String names[] = fileName.split("\\.");
		
    	if (!image.isEmpty()) {
    		//path自己定義
    		
    	        String todayDate=DateUtils.dateTime();
    		    String sname = fileName.substring(fileName.lastIndexOf("."));//獲取後綴名
    	        long timeStamp = System.currentTimeMillis();//獲取時間戳
				//此路徑自己定義
				String path1 = "/app/image/"+todayDate;//此路徑不帶圖片,用於上傳
				String imageName=timeStamp+sname;//圖片名
				File targetFile1 = new File(path1, imageName);
				String path=path1+"/"+imageName;//此路徑保存到數據庫
				File dir=targetFile1.getParentFile();
				if (!dir.exists()) {
					dir.mkdirs();
				}
                OutputStream out=null;
			    InputStream in=null;             
			    int length;
         try {    
    	  	out = new BufferedOutputStream(new FileOutputStream(targetFile1));
			in = new BufferedInputStream(image.getInputStream());
            byte[] buf = image.getBytes();//文件二進制
            while ((length = in.read(buf)) != -1) {
                out.write(buf, 0, length);
                out.flush();
            }
            in.close();
            out.close();
            } catch (IOException e) {
                e.printStackTrace();
                System.out.println(e.getMessage());
            } 
           map.put("code", 0);
           map.put("path", path);
       }else {
    	   map.put("code", 500);
           map.put("path", "");
       }
       return map;
	}
	

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章