前端代码
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%request.setAttribute("ctx", request.getContextPath());%>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="${ctx}/css/bootstrap.min.css">
<link rel="stylesheet" href="${ctx}/css/bootstrap-theme.min.css">
<script src="${pageContext.request.contextPath}/js/jquery-1.11.3.js"></script>
<script type="text/javascript">
selectFile = () => {
/*let file = new FormData();: 创建一个新的 FormData 对象,
用于将表单数据以键值对的形式存储,并用于发送到服务器。*/
let file = new FormData();
/*将选择的文件添加到 FormData 对象中。通过 $("#myfile")[0].files[0] 获取文件上传控件的第一个文件,
然后将其作为值添加到 FormData 对象中,键名为 "file"。*/
file.append("file", $("#myfile")[0].files[0]);
$.ajax({
url: "/file/images",
data: file,
dataType: "json",//返回值参数
processData: false,//禁止 jQuery 对数据进行处理,以便正确传输 FormData 类型的数据。
contentType: false,//禁止 jQuery 对数据进行处理,以便正确传输 FormData 类型的数据。
async: false,
type:"post",
success: function (r) {
alert(r.msg);
if (r.status) {
/*将返回的图片地址设置为 id 为 myphoto 的元素的 src 属性,用于展示上传的图片。*/
$("#myphoto").prop("src", "/images/" + r.data);
/*将返回的图片地址填充到 id 为 adress 的元素中*/
$("#adress").val(r.data);
}
}
})
}
</script>
</head>
<body>
<p>请选择图片:
<%--<input type="file">: 这个 <input> 标签的 type 属性被设置为 "file",表示这是一个文件上传控件,会显示一个文件选择对话框供用户选择文件。
multiple: 这个属性表示允许用户选择多个文件进行同时上传。如果不设置 multiple 属性,用户只能选择单个文件进行上传。--%>
<input type="file" multiple name="myfile" id="myfile" onchange="selectFile();"><br>
<img src="#" width="200" height="50" id="myphoto">
<input type="text" id="adress">
</p>
</body>
</html>
后端:
package www.com.practice.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
/**
* @Date: 2024/3/3 18:34
* @Description:用于图片回显的控制层
*/
@Controller
@RequestMapping("/file")
public class FileController {
@RequestMapping("/photo")
public String photo() {
return "photo";
}
/**
* @description:处理上传图片的方法,使用了Spring框架的MultipartFile来接收上传的
* 文件,并通过HttpServletRequest获取相关信息
* @param multipartFile 是Spring框架提供的用于处理文件上传的接口,通常用于接收客户端上传的文件数据
* @param request
* @return: java.util.Map
* @auther: cyl
* @date: 2024/3/5 16:19
*/
@PostMapping("/images")
@ResponseBody
public Map images(
@RequestParam("file") MultipartFile multipartFile,
HttpServletRequest request
) throws IOException {
Map<String, Object> map = new HashMap<>();
/*获取文件的大小 单位bt字节*/
long size = multipartFile.getSize();
/*判断大小*/
if (size>=1024*1024*3) {
map.put("status",false);
map.put("msg","支持上传的文件大小最大为3M");
return map;
}
/*获取文件的类型*/
String type = multipartFile.getContentType();
System.out.println("接收到的参数类型为:"+type);
String fileType = "jpg";
if ("/image/jpg".equals(type)){
fileType = "jpg";
}
if ("/image/png".equals(type)) {
fileType = "png";
}
/*设置文件命名 防止重名*/
String fileName=UUID.randomUUID().toString().replaceAll("-","")+"."+fileType;
/*获取下载地址 这两个方法选择一个*/
String filePath1=request.getSession().getServletContext().getRealPath("/")+"images";
String filePath2=request.getServletContext().getRealPath("/")+"images";
System.out.println("地址一为:"+filePath1);
System.out.println("地址二为:"+filePath2);
File file = new File(filePath1);
/*判断该文件夹是否存在 不存在就创建*/
if (!file.exists()) {
file.mkdirs();
}
/*
这行代码用于将上传的文件保存到指定的路径。在这行代码中,
multipartFile 是 MultipartFile 类型的对象,表示上传的文件;
filePath1 是保存文件的目录路径;fileName 是要保存的文件名。
*/
multipartFile.transferTo(new File(filePath1 + "/" + fileName));
map.put("status",true);
map.put("data",fileName);
return map;
}
}