java圖片上傳(1)-----使用springmvc的文件上傳功能


圖片上傳功能很多地方都有用到,最典型的就是上傳頭像,上傳身份證什么的。

本篇博客介紹springmvc框架上面org.springframework.web.multipart.commons.CommonsMultipartResolver的上傳文件功能(使用ajax提交,本篇不介紹壓縮,可能的話也是后端壓縮):

1、首先pom文件要導入一些jar包

<!-- 上傳組件包 -->
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.1</version>
        </dependency>
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>
        <dependency>
            <groupId>commons-codec</groupId>
            <artifactId>commons-codec</artifactId>
            <version>1.9</version>
        </dependency>

 

2、要確定springmvc中配置了這個功能(圖片上傳其實就是文件上傳)

3、然后我們來寫前端代碼:

元素(一個隱藏域是用來保存后端返回的服務器上面圖片路徑。比如:/images/123213213.jpg):

重點:form表單上enctype="multipart/form-data"一定要加

<form method="post" id="signupForm" enctype="multipart/form-data">
  <input type="file" id="img" name="img"/>
  <img id="picture" style="width:400px;height:400px;display:none" />   <input type="hidden" name="headImg" id="headImg"/>
</form>

js代碼如下:

因為是ajax提交的,所以要導入<script type="text/javascript" src="../sources/js/jquery.form.js"></script>插件。

<script>
$(function(){
	var prefixUrl="localhost:8081";
	
	$("#img").change(function(){
            upload(prefixUrl)
	})
})

function upload(prefixUrl){
	var options={
			type:"post",
			url:"http://"+prefixUrl+"/uploadImg",
			dataType:"json",
			cache:false,
			success:function(data){
				$("#picture").attr("src","http://"+data.webUrl)
				$("#picture").show()
				$("#headImg").val(data.path)
			}
	}
	$("#signupForm").ajaxSubmit(options)
}
</script>            

 4、controller代碼:

@RequestMapping(value="/uploadImg",method={RequestMethod.POST})
	public @ResponseBody String uploadImg(HttpServletRequest request,@RequestParam(value="img") MultipartFile pic){
//		String username=request.getParameter("username");
//		Integer count=userService.insert(username, password);
		//獲取圖片原始文件名
		String originalFileName=pic.getOriginalFilename();
		String name=""+System.currentTimeMillis();
		//獲取后綴
		String extension=originalFileName.substring(
				originalFileName.lastIndexOf("."), originalFileName.length());
		//相對路徑
		String path="/WEB-INF/sources/upload/"+name+extension;
		//絕對路徑
		String url=request.getSession().getServletContext().getRealPath("")+path;
		//網站路徑
		String webUrl=request.getRequestURL()+path;
		webUrl=webUrl.replaceAll("http://", "").replaceAll("/uploadImg/WEB-INF", "");
		webUrl="{\"webUrl\":\""+webUrl+"\",\"path\":\"/sources/upload/"+name+extension+"\"}";
		File dir=new File(url);
		if(!dir.exists()){
		  dir.mkdirs();
		}
		//上傳圖片
		try {
			pic.transferTo(new File(url));
		} catch (IllegalStateException | IOException e) {
			e.printStackTrace();
		}
		return webUrl;
	}

 結果:


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM