本文通过使用 JQuery 、AjaxUpload异步头像上传并实现实时预览**
效果预览如下
如果上传图片后,项目图片文件夹不能显示上传图片,页面也不能展示图片,手动刷新后就能看到,解决方法:
需要自己设置Myeclipse : Window---->Preferences---->General---->Workspace
jsp页面在线引用JQ
<script src="https://code.jquery.com/jquery-3.3.1.min.js"
type="text/javascript"></script>
1.AjaxUploadFile.jsp 在前端页面javascript中实现ajax异步刷新,展示上传头像
<%@ 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>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<!-- 在线引用jquery -->
<script src="https://code.jquery.com/jquery-3.3.1.min.js"
type="text/javascript"></script>
<script type="text/javascript">
function doUpload() {
var formData = new FormData($("#uploadForm")[0]);//构造FormData对象
$.ajax({
url : 'AjaxUploadFile',//接受请求的Servlet地址
type : 'POST',
data : formData,
async : false,//同步请求
cache : false,//不缓存页面
contentType : false,//当form以multipart/form-data方式上传文件时,需要设置为false
processData : false,//如果要发送Dom树信息或其他不需要转换的信息,请设置为false
success : function(url) {
$("#img_test").attr('src', url);//上传成功后,把服务器获取到的图片路径绑定到img标签是src属性上
},
error : function(returndata) {
alert(returndata);
}
});
}
</script>
</head>
<body>
<!-- form表单,注意没有action、method、enctype属性-->
<form id="uploadForm">
<label for="file">头像:</label>
<input type="file" name="file" id="file" />
<input type="button" value="上传" onclick="doUpload()" />
</form>
<img id="img_test" alt="" Style="height:50px;width: 50ps;border-radius: 50%;"/>
</body>
</html>
2.AjaxUploadFile.java servlet对页面信息进行处理,判断是否为图片,并保存在项目中
package com.iflyte.uploadtest;
import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletContext;
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.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import com.iflyte.dao.pic;
/**
* Servlet implementation class UploadFile
*/
@WebServlet("/AjaxUploadFile")
public class AjaxUploadFile extends HttpServlet {
private static final long serialVersionUID = 1L;
public AjaxUploadFile() {
super();
// TODO Auto-generated constructor stub
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//借助工具解析
//判断传入的是否是文件类型
boolean isMultipart =ServletFileUpload.isMultipartContent(request);
if(isMultipart){
//创建FileItem对象工厂
DiskFileItemFactory factory = new DiskFileItemFactory();
//获取临时文件夹
ServletContext servletContext = this.getServletConfig().getServletContext();
//获取临时文件夹
File repository = (File) servletContext.getAttribute("javax.servlet.context.tempdir");
factory.setRepository(repository);
//创建文件上传处理器
ServletFileUpload upload = new ServletFileUpload((FileItemFactory) factory);
//解决中文乱码参数
upload.setHeaderEncoding("utf-8");
List<FileItem> items = null;
try {
items = upload.parseRequest(request);
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String fileName = "";
for(FileItem item:items) {
if(!item.isFormField()) {
fileName=saveFile(item);
}
}
//把图片的路径传给页面
response.getWriter().write(fileName);
//把路径传递给数据库
pic p = new pic();
p.getpic(fileName);
}
}
private String saveFile(FileItem item) {
//获取上传图片名称
String fileFullName = item.getName();
File fileInfo = new File(fileFullName);
String fileName = fileInfo.getName();
//获取当前项目的根目录
String root ="D:\\Users\\Administrator\\eclipse-workspace\\AjaxUpload\\WebContent";
//保存路径为当前工程根目录的upload文件夹
File savePath = new File(root+File.separator+"upload");
//如果路径不存在,就新建目录
if(!savePath.exists()) {
savePath.mkdir();
}
File uploadedFile = new File(savePath+File.separator+fileName);
try {
item.write(uploadedFile);//写入
//文件的服务路径:工程目录+upload+文件名
return this.getServletContext().getContextPath()+"//upload//"+fileName;
} catch (Exception e) {
// TODO Auto-generated catch block
System.out.println("保存文件失败");
return "";
}
}
private List<FileItem> getRequestFileItems(HttpServletRequest request) {
// TODO Auto-generated method stub
return null;
}
}
3.JDBCUtils.java 把数据库连接封装成一个类,直接调用
public static Connection getConnection()
{
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/touxiang?useUnicode=true&characterEncoding=UTF-8", "root", "");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return conn;
}
4.pic.java 把图片路径保存到数据库
package com.iflyte.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import com.iflyte.jdbc.JDBCUtils;
public class pic {
public void getpic(String fileName){
//调用数据库封装函数
Connection conn = (Connection) JDBCUtils.getConnection();
String sql="insert into tbl_pic(pic) values(?)";
try {
PreparedStatement pre = (PreparedStatement) conn.prepareStatement(sql);
pre.setString(1, fileName);
pre.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
欢迎关注,共同学习!