前端页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>文件上传</title>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/bootstrap.min.js"></script>
<script type="text/javascript" src="js/main.min.js"></script>
</head>
<body>
<img src="" style="height: 120px;width:120px" id="headImg">
上传头像<input type="file" name="headImg" id="img">
<script>
$(document).ready(function() {
$("#img").change(function(){
//1.创建FormData对象 专门用于文件上传的对象
var fd = new FormData();
//2.得到要上传的文件
var file = $("#img")[0].files[0];
//3.将文件放入到formdata中
fd.append("headImg",file);
//4.发送文件
$.ajax({
url:"/woniumall777777/file/upload",
type:"post",
data:fd,
//是否序列化数据,文件本身就是二进制的数据,所以不需要序列化
processData:false,
//告知服务器将提交的数据当做普通文件处理
contentType:false,
success:function(res){
$("#headImg").prop("src",res.data);
}
});
});
});
servlet层
import java.io.File;
import java.io.IOException;
import java.util.UUID;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import com.woniu.entity.User;
import com.woniu.service.UserService;
import com.woniu.service.impl.UserServiceImpl;
import com.woniu.utils.SendDataUtil;
import com.woniu.utils.UserUtil;
@WebServlet("/file/upload")
@MultipartConfig
public class FileServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public FileServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取文件对象
Part file=request.getPart("headImg");
//获取文件名
String fileName = file.getSubmittedFileName();
//获取文件存储的路径
String path = request.getServletContext().getRealPath("");
File root =new File(path);
File webapps=root.getParentFile();
//得到存放文件的目录
File upload= new File(webapps, "upload");
//判断文件是否存在
if(!upload.exists()){
//创建文件夹
upload.mkdirs();
}
//处理文件名
String radom_name=UUID.randomUUID().toString();
//得到文件后缀名
String sufix=fileName.substring(fileName.lastIndexOf("."));
fileName=radom_name+sufix;
//得到存放文件的目录
File dest=new File(upload, fileName);
//写入文件
file.write(dest.getAbsolutePath());
int userid=(int)request.getSession().getAttribute("uid");
User user =new User().setId(userid).setAvatar(fileName);
UserService userService =new UserServiceImpl();
int result = userService.updateHeading(user);
UserUtil userUtil =new UserUtil();
if(result>0){
userUtil.setStatus(UserUtil.SUCCESS);
userUtil.setData("/upload/"+fileName);
}
SendDataUtil.writeData(response, userUtil);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
如果是springboot项目
@RestController
@RequestMapper("file")
public class FileController {
@GetMapper("upload")
protected void fileUpload(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获取文件对象
Part file=request.getPart("headImg");
//获取文件名
String fileName = file.getSubmittedFileName();
//获取文件存储的路径
String path = request.getServletContext().getRealPath("");
File root =new File(path);
File webapps=root.getParentFile();
//得到存放文件的目录
File upload= new File(webapps, "upload");
//判断文件是否存在
if(!upload.exists()){
//创建文件夹
upload.mkdirs();
}
//处理文件名
String radom_name=UUID.randomUUID().toString();
//得到文件后缀名
String sufix=fileName.substring(fileName.lastIndexOf("."));
fileName=radom_name+sufix;
//得到存放文件的目录
File dest=new File(upload, fileName);
//写入文件
file.write(dest.getAbsolutePath());
int userid=(int)request.getSession().getAttribute("uid");
User user =new User().setId(userid).setAvatar(fileName);
UserService userService =new UserServiceImpl();
int result = userService.updateHeading(user);
UserUtil userUtil =new UserUtil();
if(result>0){
userUtil.setStatus(UserUtil.SUCCESS);
userUtil.setData("/upload/"+fileName);
}
SendDataUtil.writeData(response, userUtil);
}
}
积累点滴,做好自己~