如何用SpringMVC实现同步上传图片

我这里创建的是maven项目

(1)创建一个添加页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>添加视频资源</title>
</head>
<body>
	<center>
		<h1>保利视频后台添加视频资源</h1>
		<form action="addVideo" style="font-size: 14px;" method="post"
			ENCTYPE="multipart/form-data">
			<table>
				<tr>
					<td>视频名称:</td>
					<td><input type="text" name=videoName></td>
				</tr>
				<tr>
					<td>优酷播放URL:</td>
					<td><textarea rows="10" cols="30" name="videoHtml"></textarea></td>
				</tr>
				<tr>
					<td>上传封面:</td>
					<td><input type="file" name="file"></td>
				</tr>
				<tr> <td colspan="2"><input type="submit" value="提交"></td></tr>
			</table>
		</form>
	</center>
</body>
</html>

(2)创建一个controller

/**
	 * 添加视频元素
	 * @param file
	 * @param videoInfo
	 * @param req
	 * @param res
	 * @return
	 */
	@RequestMapping("/addVideo")
	public String addVideo(@RequestParam(value = "file", required = false) MultipartFile file, VideoInfo videoInfo,
			HttpServletRequest req, HttpServletResponse res) {
		try {
			// 获取当前上下文
			String path = req.getSession().getServletContext().getRealPath("/static/imgs");
			// 文件名称
			String newName = System.currentTimeMillis() + ".png";
			File targetFile = new File(path, newName);
			// 文件夹不存在,则创建文件夹
			if (!targetFile.exists()) {
				targetFile.mkdirs();
			}
			// 保存
			try {
				file.transferTo(targetFile);
			} catch (Exception e) {
				log.error(e);
			}
			videoInfo.setVideoUrl(newName);
			videoInfoService.addVideoInfo(videoInfo);
			req.setAttribute("result", "封面上传成功!");
			return "redirect:/videoManag";
		} catch (Exception e) {
			log.error(e);
			req.setAttribute("result", "上传失败!");
			return LOCAVIDEO;
		}
	}

注意:上传后的图片是存放在eclipse所用的tomcat虚拟的一个临时文件夹下的webapp目录里面



猜你喜欢

转载自blog.csdn.net/qq_35393693/article/details/80423221