Home Java JavaBase Java implements uploading pictures to the server

Java implements uploading pictures to the server

Nov 23, 2019 pm 03:40 PM
java upload picture accomplish server

Java implements uploading pictures to the server

实现的思路:

工具:MySQL,eclipse

首先,在MySQL中创建了两个表,一个t_user表,用来存放用户名,密码等个人信息,一个t_touxiang表,用来存放上传的图片在服务器中的存放路径,以及图片名字和用户ID,T_touxiang表中的用户ID对应了t_user中的id。

t_user表SQL:

DROP TABLE IF EXISTS `t_user`;
CREATE TABLE `t_user` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `username` varchar(20) NOT NULL,
  `password` varchar(255) NOT NULL,
  PRIMARY KEY (`id`),
  UNIQUE KEY `username` (`username`)
) ENGINE=InnoDB AUTO_INCREMENT=22 DEFAULT CHARSET=utf8;
Copy after login

T_touxiang表SQL:

DROP TABLE IF EXISTS `t_touxiang`;
CREATE TABLE `t_touxiang` (
  `id` int(10) NOT NULL AUTO_INCREMENT,
  `image_path` varchar(255) DEFAULT NULL,
  `user_id` int(11) DEFAULT NULL,
  `old_name` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`),
  KEY `img_user` (`user_id`),
  CONSTRAINT `img_user` FOREIGN KEY (`user_id`) REFERENCES `t_user` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;
Copy after login

首先,写一个UploadServlet.java,用来处理图片文件的上传,并将图片路径,图片名称等信息存放到t_touxiang数据表中,代码如下:

@WebServlet("/UploadServlet.do")
public class UploadServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    protected void service(HttpServletRequest request, HttpServletResponse response)
	    throws ServletException, IOException {
	// 判断上传表单是否为multipart/form-data类型
	HttpSession session = request.getSession();
	User user = (User) session.getAttribute("user"); // 在登录时将 User 对象放入了会话中
	if (ServletFileUpload.isMultipartContent(request)) {
	    try {
		// 1. 创建DiskFileItemFactory对象,设置缓冲区大小和临时文件目录
		DiskFileItemFactory factory = new DiskFileItemFactory();
		// System.out.println(System.getProperty("java.io.tmpdir"));//默认临时文件夹
		// 2. 创建ServletFileUpload对象,并设置上传文件的大小限制。
		ServletFileUpload sfu = new ServletFileUpload(factory);
		sfu.setSizeMax(10 * 1024 * 1024);// 以byte为单位 不能超过10M 1024byte =
						 // 1kb 1024kb=1M 1024M = 1G
		sfu.setHeaderEncoding("utf-8");
		// 3.
		// 调用ServletFileUpload.parseRequest方法解析request对象,得到一个保存了所有上传内容的List对象。
		@SuppressWarnings("unchecked")
		List<FileItem> fileItemList = sfu.parseRequest(request);
		Iterator<FileItem> fileItems = fileItemList.iterator();
		// 4. 遍历list,每迭代一个FileItem对象,调用其isFormField方法判断是否是上传文件
		while (fileItems.hasNext()) {
		    FileItem fileItem = fileItems.next();
		    // 普通表单元素
		    if (fileItem.isFormField()) {
			String name = fileItem.getFieldName();// name属性值
			String value = fileItem.getString("utf-8");// name对应的value值
			System.out.println(name + " = " + value);
		    }
		    // <input type="file">的上传文件的元素
		    else {
			String fileName = fileItem.getName();// 文件名称
			System.out.println("原文件名:" + fileName);// Koala.jpg
			String suffix = fileName.substring(fileName.lastIndexOf(&#39;.&#39;));
			System.out.println("扩展名:" + suffix);// .jpg
			// 新文件名(唯一)
			String newFileName = new Date().getTime() + suffix;
			System.out.println("新文件名:" + newFileName);// image\1478509873038.jpg
			// 5. 调用FileItem的write()方法,写入文件
			File file = new File("D:/lindaProjects/mySpace/wendao/WebContent/touxiang/" + newFileName);
			System.out.println(file.getAbsolutePath());
			fileItem.write(file);
			// 6. 调用FileItem的delete()方法,删除临时文件
			fileItem.delete();
			/*
			 * 存储到数据库时注意 1.保存源文件名称 Koala.jpg 2.保存相对路径
			 * image/1478509873038.jpg
			 * 
			 */
			if (user != null) {
			    int myid = user.getId();
			    String SQL = "INSERT INTO t_touxiang(image_path,user_id,old_name)VALUES(?,?,?)";
			    int rows = JdbcHelper.insert(SQL, false, "touxiang/" + newFileName, myid, fileName);
			    if (rows > 0) {
				session.setAttribute("image_name", fileName);
				session.setAttribute("image_path", "touxiang/" + newFileName);
				response.sendRedirect(request.getContextPath() + "/upImage.html");
			    } else {
			    }
			} else {
			    session.setAttribute("loginFail", "请登录");
			    response.sendRedirect(request.getContextPath() + "/login.html");
			}
		    }
		}
	    } catch (FileUploadException e) {
		e.printStackTrace();
	    } catch (Exception e) {
		e.printStackTrace();
	    }
	}
    }
}
Copy after login

在完成图片上传并写入数据库的同时,将图片路径通过session的方式发送到HTML界面

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>更换头像</title>
</head>
<body>
         <formaction="UploadServlet.do" method="post"enctype="multipart/form-data">
                     本地目录:<inputtype="file" name="uploadFile">
           <img src="${image_path}" width="200" height="200">
                <inputtype="submit" value="上传头像"/>
   </form>
</body>
</html>
Copy after login

至此,图片上传数据库和本地服务器已经实现。

推荐教程:java入门教程

The above is the detailed content of Java implements uploading pictures to the server. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Perfect Number in Java Perfect Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Perfect Number in Java. Here we discuss the Definition, How to check Perfect number in Java?, examples with code implementation.

Weka in Java Weka in Java Aug 30, 2024 pm 04:28 PM

Guide to Weka in Java. Here we discuss the Introduction, how to use weka java, the type of platform, and advantages with examples.

Smith Number in Java Smith Number in Java Aug 30, 2024 pm 04:28 PM

Guide to Smith Number in Java. Here we discuss the Definition, How to check smith number in Java? example with code implementation.

Java Spring Interview Questions Java Spring Interview Questions Aug 30, 2024 pm 04:29 PM

In this article, we have kept the most asked Java Spring Interview Questions with their detailed answers. So that you can crack the interview.

Break or return from Java 8 stream forEach? Break or return from Java 8 stream forEach? Feb 07, 2025 pm 12:09 PM

Java 8 introduces the Stream API, providing a powerful and expressive way to process data collections. However, a common question when using Stream is: How to break or return from a forEach operation? Traditional loops allow for early interruption or return, but Stream's forEach method does not directly support this method. This article will explain the reasons and explore alternative methods for implementing premature termination in Stream processing systems. Further reading: Java Stream API improvements Understand Stream forEach The forEach method is a terminal operation that performs one operation on each element in the Stream. Its design intention is

TimeStamp to Date in Java TimeStamp to Date in Java Aug 30, 2024 pm 04:28 PM

Guide to TimeStamp to Date in Java. Here we also discuss the introduction and how to convert timestamp to date in java along with examples.

Java Program to Find the Volume of Capsule Java Program to Find the Volume of Capsule Feb 07, 2025 am 11:37 AM

Capsules are three-dimensional geometric figures, composed of a cylinder and a hemisphere at both ends. The volume of the capsule can be calculated by adding the volume of the cylinder and the volume of the hemisphere at both ends. This tutorial will discuss how to calculate the volume of a given capsule in Java using different methods. Capsule volume formula The formula for capsule volume is as follows: Capsule volume = Cylindrical volume Volume Two hemisphere volume in, r: The radius of the hemisphere. h: The height of the cylinder (excluding the hemisphere). Example 1 enter Radius = 5 units Height = 10 units Output Volume = 1570.8 cubic units explain Calculate volume using formula: Volume = π × r2 × h (4

Create the Future: Java Programming for Absolute Beginners Create the Future: Java Programming for Absolute Beginners Oct 13, 2024 pm 01:32 PM

Java is a popular programming language that can be learned by both beginners and experienced developers. This tutorial starts with basic concepts and progresses through advanced topics. After installing the Java Development Kit, you can practice programming by creating a simple "Hello, World!" program. After you understand the code, use the command prompt to compile and run the program, and "Hello, World!" will be output on the console. Learning Java starts your programming journey, and as your mastery deepens, you can create more complex applications.

See all articles