springboot实现图片上传( 二 )



springboot实现图片上传

文章插图

springboot实现图片上传

文章插图

4第四步:编写代码 。
1、前端代码
<!DOCTYPE html>
<html>


<head>
<title>图片上传</title>
<meta name="keywords" content="keyword1,keyword2,keyword3"></meta>
<meta name="description" content="this is my page"></meta>
<meta name="content-type" content="text/html; charset=UTF-8"></meta>
</head>


<body>
<form enctype="multipart/form-data" method="post" action="/testUploadimg"> 
图片:<input type="file" name="file" /><br/> 
<input type="submit" value=https://vvvtt.com/article/"上传" />.
</form>
</body>


</html>

springboot实现图片上传

文章插图

5第五步:节制器UploadController实现 。
UploadController 本家儿要分为3部门
2.1 调整页面请求goUploadImg


2.2 上传请求方式uploadImg


2.3 存储图片方式uploadFile


@Controllerpublic class UploadController {    
//跳转到上传文件的页面    
@RequestMapping(value = https://vvvtt.com/article/"/gouploadimg", method = RequestMethod.GET)
public String goUploadImg() {        
//跳转到 templates 目次下的 uploadimg.html        
return "uploadimg";    
}    
//处置文件上传    
@ResponseBody //返回json数据    
@RequestMapping(value = https://vvvtt.com/article/"/testUploadimg", method = RequestMethod.POST)
public String uploadImg(@RequestParam("file") MultipartFile file,                            
HttpServletRequest request) {        
tring contentType = file.getContentType();        
String fileName = file.getOriginalFilename();        
String filePath = "D:/img";        
if (file.isEmpty()) {            
return "文件为空!";        
}        
try {            
uploadFile(file.getBytes(), filePath, fileName);        
} catch (Exception e) {            
// TODO: handle exception        
}        
//返回json        
return "上传当作功";    
}    
public static void uploadFile(byte[] file, String filePath, String fileName) throws Exception {        
File targetFile = new File(filePath);        
if (!targetFile.exists()) {            
targetFile.mkdirs();        
}        
FileOutputStream out = new FileOutputStream(filePath +"/"+ fileName);        
out.write(file);        
out.flush();        
out.close();    
}
}

springboot实现图片上传

文章插图

推荐阅读