JavaWeb实现图片上传并显示

1.创建maven项目,打包格式为war,导入maven依赖 pom文件。

使用了common fileupload 处理文件上传

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>Face</groupId>
  <artifactId>FaceTest</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>war</packaging>
<dependencies>
    <!-- Servlet API -->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
      <scope>provided</scope>
    </dependency>
<dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.3</version>
</dependency>
<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.6</version>
</dependency>
    <dependency>  
      <groupId>commons-lang</groupId>  
      <artifactId>commons-lang</artifactId>  
      <version>2.6</version>  
      <scope>provided</scope>  
    </dependency>
    <!-- https://mvnrepository.com/artifact/log4j/log4j -->
  </dependencies>
  <build>
    <sourceDirectory>src/main/java</sourceDirectory>
    <plugins>
      <plugin>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.5.1</version>
        <configuration>
          <source>1.8</source>
          <target>1.8</target>
        </configuration>
      </plugin>
      <!-- Embedded Apache Tomcat required for testing war -->
      <plugin>
        <groupId>org.apache.tomcat.maven</groupId>
        <artifactId>tomcat7-maven-plugin</artifactId>
        <version>2.2</version>
        <configuration>
          <path>/</path>
        </configuration>
      </plugin>
    </plugins>
  </build>
  
</project>

2.创建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>
<%String ctxPath=request.getContextPath(); %>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="<%=ctxPath%>/upload" method="post" enctype="multipart/form-data">
<input  type="file" name="images"> 
<button  type="submit"  name="upload">上传</button>
</form>
</body>
</html>

3.后台处理页面,上传成功返回index.jsp


文件的名称以及文件的保存路径,将文件保存在images目录下


我们尽量不要将图片放在WEB-INF下 读取起来比较麻烦

将文件上传保存在images里 并将文件路径保存在数据库中 这样就可以实现图片的上传与展示了

package faceImages;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

@WebServlet("/upload")
public class UploadServlet extends HttpServlet {
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
		req.getRequestDispatcher("/WEB-INF/upfile.jsp").forward(req, resp);
	}

	/**
	 * 解析上传的图片路径 图片的信息
	 */
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {

		req.setAttribute("message", "");
		req.setAttribute("path", "");
		String filename = null;
		// 设置上传图片的保存路径
		String savePath = this.getServletContext().getRealPath("/images");
		File file = new File(savePath);
		// 判断上传文件的保存目录是否存在
		if (!file.exists() && !file.isDirectory()) {
			System.out.println(savePath + "目录不存在,需要创建");
			// 创建目录
			file.mkdir();
		}
		DiskFileItemFactory factory = new DiskFileItemFactory();
		// 2、创建一个文件上传解析器
		ServletFileUpload upload = new ServletFileUpload(factory);
		upload.setHeaderEncoding("UTF-8");
		// 3、判断提交上来的数据是否是上传表单的数据
		if (!ServletFileUpload.isMultipartContent(req)) {
			// 按照传统方式获取数据
			return;
		}
		try {
			List<FileItem> list = upload.parseRequest(req);
			System.out.println(list.toString());// 文件的路径 以及保存的路径
			for (FileItem item : list) {
				 filename = item.getName();// 获得一个项的文件名称
				if (filename == null || filename.trim().equals("")) {// 如果為空則跳過
					continue;
				}
				// 報錯 需要過濾文件名稱 java.io.FileNotFoundException:
				// G:\测试02\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\FaceUp\WEB-INF\images\C:\Users\Ray\Pictures\2.jpeg
				// (文件名、目录名或卷标语法不正确。)

				filename = filename.substring(filename.lastIndexOf("\\") + 1);
//				System.out.print(filename);
				if (filename.substring(filename.lastIndexOf(".") + 1).equals("png")
						|| filename.substring(filename.lastIndexOf(".") + 1).equals("jpg")
						|| filename.substring(filename.lastIndexOf(".") + 1).equals("jpeg")) {
					InputStream in = item.getInputStream();// 獲得上傳的輸入流
					FileOutputStream out = new FileOutputStream(savePath + "\\" + filename);// 指定web-inf目錄下的images文件
					req.setAttribute("path",  "images"+"\\" + filename);

					int len = 0;
					byte buffer[] = new byte[1024];
					while ((len = in.read(buffer)) > 0)// 每次讀取
					{
						out.write(buffer, 0, len);
					}
					in.close();
					out.close();
					item.delete();
				} else {  //必须是图片才能上传否则失败
					return ;
				}
			}
		} catch (FileUploadException e) {
			e.printStackTrace();
		}
		req.setAttribute("message", "上传成功");
		req.getRequestDispatcher("/WEB-INF/index.jsp").forward(req, resp);
	}
}

4.运行测试

上传成功啦,将上传路径保存在数据库就可以实现图片的上传已经显示了

如果需要做头像上传的话 则需要使用jquery对图片的大小进控制 这样头像上传就可以完成了





猜你喜欢

转载自blog.csdn.net/RAVEEE/article/details/80897017