1. 程式人生 > >SpringMVC單圖片上傳至資料庫和回顯

SpringMVC單圖片上傳至資料庫和回顯

在登入時上傳一個圖片以及回顯。之前,需要匯入兩個jar包:commons-fileupload-1.3.1和commons-io-2.4。

Index.jsp頁面:

一定要寫 enctype="multipart/form-data",否則springmvc就會解析失敗。這個的作用就是將form表單的資料以二進位制的方式傳輸。

<body>
	<form action="${pageContext.request.contextPath }/user/upload.do" method="post" enctype="multipart/form-data">  
 		<table>
 			<tr>
 				<td>使用者名稱:</td>
 				<td><input type="text" name="name"></td>
 			</tr>
 			<tr>
 				<td>密碼:</td>
 				<td><input type="password" name="password"></td>
 			</tr>
 			<tr>
 				<td>圖片:</td>
 				<td><input type="file" name="file"></td>
 			</tr>
 			<tr>
 				<td></td>
 				<td><input type="submit" value="上傳"></td>
 			</tr>
 		</table>
 	</form>  
</body>

success.jsp回顯頁面 :

<body>
<c:forEach items="${userList}" var="userList" >
	使用者名稱:${userList.name}<br>
	密碼:${userList.password }<br>
	<!--拼接圖片回顯的的URL-->
	<img  src="${pageContext.request.contextPath }/${userList.image}"><br>
</c:forEach>
</body>
</html>

Springmvc的配置加入上傳檔案的配置:

<!-- 檢視解析器 -->
	<bean id="viewResolver"
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/" />
		<property name="suffix" value=".jsp"></property>
	</bean>
	
	<bean id="multipartResolver"  
    class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
    <!-- 設定上傳檔案的最大尺寸為1MB -->  
    <property name="maxUploadSize">  
        <value>1048576</value>  
    </property>  
</bean>  

實體類:

private Integer id;  
	  
    private String name;  
  
    private String password;  
      
    private String image;

Controller:

@Controller
@RequestMapping("/user")
public class UserController {

	@Autowired
	private UserService userService;
	
	@RequestMapping(value="/upload",method=RequestMethod.POST)  
    private String fildUpload(User user,@RequestParam(value="file",required=false) MultipartFile file,  
            HttpServletRequest request)throws Exception{  
				//使用UUID給圖片重新命名,並去掉四個“-”
				String name = UUID.randomUUID().toString().replaceAll("-", "");
				//獲取圖片名稱
				String imageName=file.getOriginalFilename();
				//獲得檔案型別(可以判斷如果不是圖片,禁止上傳)  
		        //String contentType=file.getContentType();  
		        //獲得檔案字尾名 
		        //String suffixName=contentType.substring(contentType.indexOf("/")+1);
				//獲取檔案的副檔名
				String ext = FilenameUtils.getExtension(file.getOriginalFilename());
				//設定圖片上傳路徑
				String filePath = request.getSession().getServletContext().getRealPath("/upload");
				System.out.println(filePath);
				//以絕對路徑儲存重名命後的圖片
				file.transferTo(new File(filePath+"/"+name + "." + ext));
				//把圖片儲存路徑儲存到資料庫
				user.setImage("upload/"+name + "." + ext);
				
				userService.add(user);
				//重定向到查詢所有使用者的Controller,測試圖片回顯
				return "redirect:/user/list.do";
	}
	//查詢所有使用者
	@RequestMapping(value = "/list")
	public String getAll(Model model) throws Exception{
		List<User> userList = userService.list();
		model.addAttribute("userList",userList);
		return "success";
	}

}

顯示圖片: