天天看点

使用Java实现文件的上传以及图片的回显

1.图解实现文件上传的步骤

使用Java实现文件的上传以及图片的回显

2.上传文件的接口MultipartFile接口

MultipartFile是一个接口(abstract interface)

public interface MultipartFile

/**

A representation of an uploaded file received in a multipart request.

其实例对象代表了一个在multipart请求中接收到的待上传文件

The file contents are either stored in memory or temporarily on disk.

而文件的内容要么存储在记忆中要么暂时存储在硬盘中

In either case, the user is responsible for copying file contents to a

在任何一种情况下,使用者都可以复制文件内容到一个

session-level or persistent store as and if desired. The temporary storages

会话级或者持久存储中

will be cleared at the end of request processing.

在请求处理结束时,临时的存储都会被清空

可以把这个类理解成一个代表型的类,

因为其实例往往用来代表要上传的文件

还有一种是做事型的类

实例化该类是为了使用该类的能做某事的方法

有些类既是代表型的又是做事型的

3.login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<base href="http://localhost:8080/SpringMVCDemo03_4/">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
	<h1>${msg }</h1>
	<form action="user/login.do">
		<p>账号:<input type="text" name="account"></p>
		<p>密码:<input type="password" name="password"></p>
		<p><input type="submit" value="登录"></p>
	</form>
</body>
</html>
           

4.UserController

package com.zhiyou100.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.zhiyou100.model.User;
import com.zhiyou100.service.UserService;
import com.zhiyou100.service.impl.UserServiceImpl;

@Controller
@RequestMapping("user")
public class UserController {
	private UserService userService = new UserServiceImpl();
	
	@RequestMapping("login.do")
	public String login(User user,HttpServletRequest request,Model model){
		String result = userService.login(user, request.getSession());
		if (result.equals("登录成功")) {
			return "redirect:info.do";
		}else {
			model.addAttribute("msg", result);
			return "forward:/login.jsp";
		}
	}
	@RequestMapping("info.do")
	public String info(){
		return "success";
	}
	@RequestMapping("update.do")
	public String update(User user,@RequestParam("icon") MultipartFile multipartFile,HttpServletRequest request){
		userService.update(user, multipartFile, request.getSession());
		return "redirect:info.do";
	}
}
           

5. UserServiceImpl

package com.zhiyou100.service.impl;

import java.io.File;

import javax.servlet.http.HttpSession;

import org.springframework.web.multipart.MultipartFile;

import com.zhiyou100.dao.UserDAO;
import com.zhiyou100.dao.impl.UserDAOImpl;
import com.zhiyou100.model.User;
import com.zhiyou100.service.UserService;

public class UserServiceImpl implements UserService{

	private UserDAO userDAO = new UserDAOImpl();
	@Override
	public String login(User user, HttpSession session) {
		if (user.getAccount() == null || user.getAccount().length() == 0) {
			return "账户名不能为空";
		}
		if (user.getPassword() == null || user.getPassword().length() == 0) {
			return "密码不能为空";
		}
		User user2 = userDAO.findByAccount(user.getAccount());
		if (user2 == null) {
			return "账户不存在";
		}
		if (!user.getPassword().equals(user2.getPassword())) {
			
			return "密码错误";
		}
		session.setAttribute("user", user2);
		return "登录成功";
	}
	@Override
	public void update(User user, MultipartFile multipartFile, HttpSession session) {
		
		User user2 =(User) session.getAttribute("user");
		user2 = userDAO.queryById(user2.getId());
		if (user.getPassword() != null && user.getPassword().length() != 0) {
			user2.setPassword(user.getPassword());	
		}
		if (!multipartFile.isEmpty()) {
			try {
				String path = session.getServletContext().getRealPath("img/");
				String fileName=  "";
				fileName+= System.currentTimeMillis();
				fileName+= session.getId();
				fileName+= multipartFile.getOriginalFilename();
				multipartFile.transferTo(new File(path+fileName));
				user2.setHeader(fileName);
			} catch (Exception e) {
			}
		}
		userDAO.update(user2);
		session.setAttribute("user", user2);
	}
}
           

6. JDBC

package com.zhiyou100.util;

import java.lang.AutoCloseable;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

public class JDBC {
	public static Connection getConnection() throws IOException, ClassNotFoundException, SQLException{
		InputStream is = JDBC.class.getClassLoader().getResourceAsStream("jdbc.properties");
		Properties properties = new Properties();
		properties.load(is);
		String driver = properties.getProperty("driver");
		String url = properties.getProperty("url");
		String user = properties.getProperty("user");
		String password = properties.getProperty("password");
		Class.forName(driver);
		Connection connection = DriverManager.getConnection(url,user,password);
		return connection;
	}
	public static void Close(AutoCloseable ...closeables){
		for (AutoCloseable closeable : closeables) {
			if (closeable!=null) {
				try {
					closeable.close();
				} catch (Exception e) {
					System.out.println("关闭失败");
					e.printStackTrace();
				}
			}
		}
	}
}
           

7. jdbc.properties

driver = com.mysql.jdbc.Driver
url = jdbc:mysql://127.0.0.1:3306/test2
user = root
password = 123456
           

8. success.jsp

<%@ 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>
<base href="http://localhost:8080/SpringMVCDemo03_4/">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
${user}
	<c:if test="${user.header ==null }">
		<img alt="" src="img/1.png">
	</c:if>
	<c:if test="${user.header !=null }">
		<img alt="" src="img/${user.header }">
	</c:if>
	<hr>
	<p>修改个人信息</p>
	<form action="user/update.do" method="post" enctype="multipart/form-data">
		<!-- 在这里可以不提交id -->
		<p>
			修改密码:<input type="text" name="password">
		</p>
		<p>
			修改头像:<input type="file" name="icon">
		</p>
		<p>
			<button>修改</button>
		</p>
	</form>
</body>
</html>
           

继续阅读