您的位置:首页 > 编程语言 > Java开发

springboot头像上传保存及显示

2017-05-02 11:03 330 查看
最近在用spring boot开发项目时,需要上传头像。但是每次在上传成功后,需要显示的时候,img标签链接总是带本地地址localhost,而上传的图片又不在项目目录下,从而导致每次都无法显示。最后通过src访问后台的方式显示头像。

图片上传代码如下:

@RequestMapping("save")
public String save(@RequestParam(value = "file") MultipartFile file, userInfo uf, RedirectAttributes attributes, HttpServletRequest request) {
if (uf != null) {
if (!file.isEmpty()) {
String fileName = UUID.randomUUID().toString().replaceAll("-", "") + file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
String filePath ="/Users/thomas-wu/upload/" + fileName;
System.out.println(filePath);
try {
file.transferTo(new File(filePath));
} catch (IOException e) {
e.printStackTrace();
}
uf.setHead_href("getimgs?address="+filePath);
}

}
String result = userService.saveUser(uf);
JSONObject jb = JSONObject.fromObject(result);
if (jb.getInt("status") == 1 && "信息保存成功".equals(jb.getString("msg"))) {
attributes.addFlashAttribute("error", "信息保存成功");
return "redirect:/user";
}
attributes.addFlashAttribute("error", "信息保存失败");
return "redirect:/edit";
}


头像显示代码如下:

@RequestMapping("/getimgs")
public void getimg(String address, HttpServletRequest request, HttpServletResponse response) throws IOException{
try {
FileInputStream hFile=new FileInputStream(address);
int i=hFile.available();
byte data[]=new byte[i];
hFile.read(data);
hFile.close();
response.setContentType("image/*");
OutputStream toClient=response.getOutputStream();
toClient.write(data);
toClient.close();
}catch (IOException e){
PrintWriter toClient=response.getWriter();
response.setContentType("text/html;charset=gb2312");
toClient.write("无法打开图片");
toClient.close();
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  spring 图片