上传文件的jsp代码
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<body>
<h2>Hello World!</h2>
<form action="${pageContext.request.contextPath}/uploadImg.form" method="post" enctype="multipart/form-data">
<input type="file" name="upload"/>
<input type="submit" name="上传">
</form>
</body>
</html>
后台的controller路径
其中request.getserveletContext是为了获取到当前程序的根目录,getRealPath是为了拿到对应路径下的文件夹
package com.ittest.controller;
import jdk.internal.cmm.SystemResourcePressureImpl;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.util.List;
import java.util.UUID;
@Controller
public class testController {
@RequestMapping(value = "/uploadImg")
public void findDataByConditions(HttpServletRequest request, HttpServletResponse response, MultipartFile upload) throws Exception {
// 上传图片 的 原名称
String oldName = upload.getOriginalFilename();
String newName = null;
//解决文件重名问题
//其中使用uuid来实现重命名,h后面hi截取文件的类型
String finalFileName = UUID.randomUUID().toString()+oldName.substring(oldName.lastIndexOf("."));
//获取文件的根路径+
String path = request.getServletContext().getRealPath("photo")+File.separator+finalFileName;
System.out.println("文件 的路径是"+path);
upload.transferTo(new File(path));
System.out.print(oldName);
}
}
实现效果:
这样通过uuid来实现出防止重复上传的效果
源代码: