上传图片、文件等,及文件夹

一、上传图片,文件(ajax上传,并返回提示信息)

前端界面(jsp,css,jquery等)

<%@ 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="multipart/form-data; charset=utf-8" />
<title>Insert title here</title>
<script type="text/javascript" src="../js/jquery-3.3.1.js"></script>
<script type="text/javascript">
function upload() {
	var  uploadfile= $("#uploadfile")[0].files[0];
	 var formData = new FormData();
     formData.append('uploadfile',uploadfile);
    $.ajax({
        async: false, 
        url:'uploadadd.do',
        type:'post',
        data:formData,
        processData:false,
        contentType:false,
        success:function (data) {
            alert(data);
        }, error:function () {
        	alert("失败");
        }
    });
}
</script>
</head>
<body>
<form  class="tabson"  enctype="multipart/form-data">
文件:<input type="file" name="uploadfile"  id="uploadfile" >
<input type="button" onclick="upload()" value="上传文件">
</form>
</body>
</html>

控制层

	@ResponseBody
	@RequestMapping(value="uploadadd.do",method=RequestMethod.POST)
	public String addAnnouncement(HttpServletRequest request, 
            @RequestParam("uploadfile") MultipartFile uploadfile) { 	
		String name=uploadfile.getOriginalFilename();
		String suffix = name.substring(name.lastIndexOf(".") + 1);
		String localPath = request.getSession().getServletContext().getRealPath("/") + "data/Img_1";
		System.out.println("商品存储路径:" + localPath);
		// 创建图片名称
		String filename = Uploadutil.getNowDate() + "." + suffix;
		System.out.println(filename+"----------");
		// 创建目录 文件夹为空就创建
		File dir = new File(localPath);
		if (!dir.exists()) {
			//System.out.println("创建的文件夹为" + dir);
			dir.mkdirs();
		}	
		// 图片绝对路径,拼接图片路径
		String realPath = dir +"/"+ filename;
		String realPath1=realPath.replace("/", "\\");
		System.out.println(realPath1.toString()+"---------------------------------");
		// 写入图片  将图片保存在服务器下
		File newFile = new File(realPath1);
		 try {
			 uploadfile.transferTo(newFile);
		 }catch( Exception e)  {
			 e.printStackTrace();
		  }
		 System.out.println("request.getContextPath():   "+request.getContextPath());
		// 拼接传输协议+域名+端口号+
		String host = img_url + request.getContextPath();
		// 数据库存储图片绝对路径
		String sqlPath = host + "/data/Img/" + filename;
		System.out.println("数据库存储的路径:" + sqlPath);	
		return "成功";
	}	

结果展示

1、界面返回成功状态
在这里插入图片描述
2、控制台打印的信息
在这里插入图片描述

二、上传excel 并解析excel内容

前端界面(jsp,css,jquery等)

<form action="uploadofexcel_1.do"  enctype="multipart/form-data"  method="post">
文件: <input type="file"     name = "uploadFile" /><br>
<input type = "submit" value = "提交">
</form>

控制层

@RequestMapping(value = "uploadofexcel_1.do", produces = "application/text; charset=utf-8")
	public String uploadofexcel_1(HttpServletRequest request,@RequestParam("uploadFile") MultipartFile uploadFile) {
		if (uploadFile.isEmpty()) {
			try {
				throw new Exception("文件不存在!");
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		InputStream in = null;
		try {
			in = uploadFile.getInputStream();
		} catch (IOException e) {
			e.printStackTrace();
		}
		List<List<Object>> listob = null;
		try {
			listob = new ExcelUtil().getBankListByExcel(in, uploadFile.getOriginalFilename());
		} catch (Exception e) {
			e.printStackTrace();
		}
		for (int i = 0; i < listob.size(); i++) {
			List<Object> lg=listob.get(i);
			System.out.println(lg);
		}
		System.out.println( uploadFile.getOriginalFilename());
		 return "redirect:ShowUpload.do";
	}

结果展示(解析excel的结果)

1、excel里的信息,解析的内容为List< List< Object>>形式,可将其转换为Lst< Object>形式。
在这里插入图片描述

三、上传文件夹

前端界面(jsp,css,jquery等)

<form action="upload3.do"  enctype="multipart/form-data"  method="post">
图片: <input type="file"     name = "pictureFile" webkitdirectory/><br>
<input type = "submit" value = "提交">
</form>

控制层

	@RequestMapping(value="upload3.do",method=RequestMethod.POST)
	public String insertpicture3(HttpServletRequest request, 
            @RequestParam("pictureFile") MultipartFile[] pictureFiles){
		List<Picture> list=new ArrayList<Picture>();
		int i=1;
		 for (MultipartFile mf : pictureFiles) {
			 if(!mf.isEmpty()) {
			// 获取文件名
			String name = mf.getOriginalFilename();
			System.out.println(name);
			// 获取文件后缀
			String suffix = name.substring(name.lastIndexOf(".") + 1);
			System.out.println("1-----"+suffix);
		/*	if (!suffix.equalsIgnoreCase("png") && !suffix.equalsIgnoreCase("gif") && !suffix.equalsIgnoreCase("jpg")
					&& !suffix.equalsIgnoreCase("jpeg") && !suffix.equalsIgnoreCase("bmp")) {
				return "文件类型错误,请上传图片文件";
			}	*/		
			String localPath = request.getSession().getServletContext().getRealPath("/") + "data/Img";
			System.out.println("商品存储路径:" + localPath);
			// 创建图片名称
		
			String filename = Uploadutil.getNowDate() +"-"+i+ "." + suffix;
			i++;
			System.out.println(filename+"----------");
			// 创建目录 文件夹为空就创建
			File dir = new File(localPath);
			if (!dir.exists()) {
				//System.out.println("创建的文件夹为" + dir);
				dir.mkdirs();
			}	
			// 图片绝对路径,拼接图片路径
			String realPath = dir +"/"+ filename;
			String realPath1=realPath.replace("/", "\\");
			System.out.println(realPath1.toString()+"---------------------------------");
			// 写入图片  将图片保存在服务器下
			File newFile = new File(realPath1);
			 try {
				 mf.transferTo(newFile);
			 }catch( Exception e)  {
				 e.printStackTrace();
			  }
			 System.out.println("request.getContextPath():   "+request.getContextPath());
			// 拼接传输协议+域名+端口号+
			String host = img_url + request.getContextPath();
			// 数据库存储图片绝对路径
			String sqlPath = host + "/data/Img/" + filename;
			System.out.println("数据库存储的路径:" + sqlPath);
			Picture pc=new Picture();
			pc.setPname(filename);
			pc.setUrls(sqlPath);
			list.add(pc);
			 }
		 }
		 for (Picture picture : list) {
			System.out.println(picture.toString());
		}
		//批量插入图片信息
		 int num=uploadserviceimpl.InsertOfPicture(list);
		 System.out.println(num);
		 return "redirect:ShowUpload.do";
	}

上传的界面及结果

1、上传文件夹的界面,webkitdirectory指向的是文件夹,若不带webkitdirectory则指向的是根目录,各种文件
上传文件夹的界面,webkitdirectory指向的是文件夹,若不带webkitdirectory则指向的是根目录,各种文件/2、Chrome浏览器带的功能,显示该文件夹下有多少个子文件
在这里插入图片描述
3、文件上传成功后显示的结果(原先有两个图片,此次上传的为4个文件)
文件上传成功后显示的结果4、控制器打印的结果,上传文件夹的信息
该文件夹下的4个文件,打印的信息

发布了15 篇原创文章 · 获赞 4 · 访问量 1467

猜你喜欢

转载自blog.csdn.net/qq_40791070/article/details/92123948