图片文件上传示例

代码片段:

//新增post
	@RequestMapping(method=RequestMethod.POST, value="/addPost")
	@ResponseBody
	public int addPost(Post post, MultipartFile file, HttpSession session) {
		try {
			if(file.getSize() > 0) {
				String path = session.getServletContext().getRealPath("upload/postImg/");//绝对路径
				System.out.println(path);
			    File targetFile = new File(path, file.getOriginalFilename());
			    file.transferTo(targetFile);
			    String p = path+file.getOriginalFilename();
			    System.out.println(p);
				post.setPostImg(file.getOriginalFilename());
				System.out.println(post.getPostImg());
				System.out.println(post);
			}    
		} catch (IllegalStateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		System.out.println(post);
		return this.postService.addPost(post);
		
	} 

springmvc-config.xml配置:


    
    
    
    
    
    
    
     
	    
	     
	   
    
	
		
		
		
	
    
        
        
    
    


本例用到了SSM框架知识,不懂得朋友可以先去了解SSM的相关知识,往后我会补上SSM的整个详细搭建流程。

你可能感兴趣的:(Java核心技术)