How to use the ssm framework to upload files?

This article will tell you how to upload pictures.
1. First, build the ssm framework and introduce 2 jar packages under the lib package under WEB-INF,
commons-fileupload-1.2.1.jar
commons- io-1.4.jar
download address: https://pan.baidu.com/s/1iNQ0ekCeTJ2tIGMqaCwFtw
Extraction code: w24t
download path My Baidu cloud disk provides a version, or you can find it online,
here we simulate users uploading avatars Example to upload pictures.

2.The index.jsp file is mainly the upload interface:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme() + "://"
			+ request.getServerName() + ":" + request.getServerPort()
			+ path + "/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting page</title>
</head>
<body>
	<form action="upload.do" method="post"
		enctype="multipart/form-data">
		<label>用户名:</label><input type="text" name="uname" required><br> <label>密码:</label><input
			type="password" name="pwd" required><br> <label>上传头像:</label><input
			type="file" name="file"><br> <input type="submit" value="展示">
	</form>
</body>
</html>

3. The show.jsp file mainly talks about uploaded files to show:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    <title>My JSP 'MyJsp.jsp' starting page</title>
  </head>
  <body>
    <h3>显示图片</h3>
    ${user.image}<br>
    <img id="image" name="image" src="images/${user.image}"><br>
        用户名:${user.uname}
  </body>
</html>

Unlike ordinary add, delete, modify, and check, we need to use the MultipartFile interface to implement image upload. Therefore, we need to add an attribute to the entity class private MultipartFile file;and generate its get and set methods.** What you need to pay attention to is: This attribute is not used to store pictures, but an auxiliary attribute for uploading pictures, that is, the database should not have this attribute.
Entity class attribute (the database is built by itself):

	 private Integer uid;
    private String uname;
    private String pwd;
    private String image;
    //辅助图片上传属性
    private MultipartFile file;

The get and set methods generate the
4.controller layer code by themselves (I named it action myself):

import java.io.File;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import com.biz.IUserService;
import com.po.Users;
@Controller
public class UsersAction {
	@Autowired
	private IUserService userService;
	public IUserService getUserService() {
		return userService;
	}
	public void setUserService(IUserService userService) {
		this.userService = userService;
	}
	@RequestMapping("upload.do")
	public String upload(Users user, HttpServletRequest request, Model model)
			throws Exception {
		// 保存数据库的路径
		String realPath = request.getSession().getServletContext().getRealPath("/");
		//String sqlPath = null;
		// 定义文件保存的本地路径
		//String localPath = "D:\\File\\";
		// 定义 文件名
		String filename = null;
		if (!user.getFile().isEmpty()) {
			// 生成uuid作为文件名称
			String uuid = UUID.randomUUID().toString().replaceAll("-", "");
			// 获得文件类型(可以判断如果不是图片,禁止上传)
			String contentType = user.getFile().getContentType();
			// 获得文件后缀名
			String suffixName = contentType
					.substring(contentType.indexOf("/") + 1);
			// 得到 文件名
			filename = uuid + "." + suffixName;
			// 文件保存路径
			user.getFile().transferTo(new File(realPath + "/images/"+ filename));
		}
		// 把图片的相对路径保存至数据库
		//sqlPath = "/images/" + filename;
		//System.out.println(sqlPath);
		user.setImage(filename);
		userService.addUser(user);
		model.addAttribute("user", user);
		return "show.jsp";
	}
}

The applicationContext.xml configuration file should add the following configuration:

    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
    <property name="defaultEncoding" value="utf-8"/>  
    <!-- 最大内存大小 -->  
    <property name="maxInMemorySize" value="10240"/>  
    <!-- 最大文件大小,-1为不限制大小 -->  
    <property name="maxUploadSize" value="-1"/>  
	</bean>
	<tx:annotation-driven transaction-manager="txmanager"/>	
此时,便可以试着运行一下!效果如下:
![在这里插入图片描述](https://img-blog.csdnimg.cn/20190710180017698.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2xxMTc1OTMzNjk1MA==,size_16,color_FFFFFF,t_70)
在这我们选择这张灰太狼照片,然后点击展示,图片将呈现出来,如下:
![在这里插入图片描述](https://img-blog.csdnimg.cn/20190710180111906.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L2xxMTc1OTMzNjk1MA==,size_16,color_FFFFFF,t_70)

At this time, the database also has relative information. The
Insert picture description here
picture is stored on the server, under Tomca!

Guess you like

Origin blog.csdn.net/lq1759336950/article/details/95355402
Recommended