Java后端SSM框架图片上传功能实现方法解析

 更新时间:2020年6月29日 08:24  点击:2398

一、技术概述

(1)这个技术是做什么

这个技术是上传图片到服务器上,并且把地址存在数据库中。前端调用的时候之间通过地址即可调用。

(2)学习该技术的原因

由于用户在写日记的时候也可以进行图片的上传,同时还有用户头像的上传。

二、技术详述

以上传用户的头像为例

(1)接口代码

	@RequestMapping(value = "user/profilePhoto", produces = "application/json; charset=utf-8")
	@ResponseBody
	public boolean imageUphold(@RequestParam("photo") MultipartFile file, Long phone) throws IOException {
		String filePath = ducumentBase;// 保存图片的路径
		// String filePath = "/image";//保存图片的路径
		// 获取原始图片的拓展名
		String originalFilename = file.getOriginalFilename();
		System.out.println("originalFilename: " + originalFilename);
		// 新的文件名字
		String newFileName = UUID.randomUUID() + originalFilename;
		// 封装上传文件位置的全路径
		filePath += "/" + phone;
		System.out.println("filePath: " + filePath);
		File targetFile = new File(filePath, newFileName);
		if (!targetFile.exists()) {
			targetFile.mkdirs();
		}
		// 把本地文件上传到封装上传文件位置的全路径
		System.out.println("newFileName: " + newFileName);

		System.out.println("targetFile: " + targetFile.getName());
		System.out.println("phone: " + phone);
		//System.out.println("afterPhone");
		try {
			file.transferTo(targetFile);
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String allPath=mappingPath + "/" + phone+ "/" + newFileName;
		System.out.println("存储路径为"+allPath);
		boolean result=onedayServiceImpl.updProfilePhoto(allPath, phone);//存在数据库中,其中allPath的数据库类型为varchar(1000)
		return result;
	}

其中的ducumentBase以及mappingPath

@Value("${ducument.base}")
private String ducumentBase;
@Value("${mapping.path}")
private String mappingPath;

为全局变量

配置文件

ducument.base = D://oneday_uphold
mapping.path = /images

(2)解释

用MultipartFile来接收图片的二进制码,然后使用路径+图片名+随机数保存图片。

(3)测试jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
  pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>image/uphold</title>
</head>
<body>
  <form action="user/profilePhoto" method="post" enctype="multipart/form-data">
    图片:<input type="file" name="photo">
    电话:<input type="text" name="phone" value="13225942005">
    <input type="submit" value="提交">
  </form>
</body>
</html>

(4)显示图片

<img id="images" alt="头像" src="/mappingPath/路径">

三、技术使用中遇到的问题和解决过程

(1)无法保存:

查看是否已进行服务器的设置,以Eclipse为例

Servers->Modules->Add External Web Modules 进行路径的设置

(2)无法访问接口:

查看是否使用表单形式访问:method="post" enctype="multipart/form-data"

同时上传的名字是否与接口相对应

四、总结

本来进行图片的上传的时候考虑过直接上传二进制到数据库用blob进行保存,但觉得这样不好,遂改为保存图片地址的方式进行上传。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持猪先飞。

[!--infotagslink--]

相关文章