栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringMvc+element实现文件上传

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringMvc+element实现文件上传

一、导入依赖

在pom.xml添加这几个依赖

  
      org.springframework
      spring-webmvc
      5.2.22.RELEASE
    
    
      commons-fileupload
      commons-fileupload
      1.4
    
  
      com.fasterxml.jackson.core
      jackson-databind
      2.13.3
    
    
      javax.servlet
      javax.servlet-api
      3.1.0
    
二、在springMVC的配置文件添加配置

   添加文件上传配置

 
        
        
三、开始配置控制器
@RequestMapping(value = "/upload",method = RequestMethod.POST)
	@ResponseBody
	public Result upload(MultipartFile file,HttpSession session) throws IOException{
        //获取服务器路径
		String path = session.getServletContext().getRealPath("/upload");
        //获取原文件名字
		String originalName = file.getOriginalFilename();
        //随机生成文件的名字
		String newName = UUID.randomUUID().toString().replace("-", "")
						+ originalName.substring(originalName.indexOf("."));

		File file1 = new File(path);
        //如果目录不存在 就创建目录
		if(!file1.exists() || !file1.isFile()){
			file1.mkdirs();
		}

		file1 = new File(file1, newName);
        //生成新名字的目标文件是否存在 不存在则创建文件
		if(!file1.exists()){
			file1.createNewFile();
		}
        //io流input读取 output写入
		try(
				InputStream read = myFile.getInputStream();
				OutputStream out = new FileOutputStream(file1);
				){
			byte[] bytes = new byte[1024];
			int ch = 0;
			while((ch = read.read(bytes)) != -1){
				out.write(bytes, 0, ch);
			}
			out.flush();
			out.close();
			return Result.success("上传成功!", "http://localhost:8080/SpringMvcLogin01/uploadupload/"+newName);
		}catch (Exception e){
			e.printStackTrace();

			return Result.error("上传失败!");
		}
	}
四、jsp页面
<%--
  Created by IntelliJ IDEA.
  User: DELL
  Date: 2022/6/9
  Time: 18:57
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    Title
        
    
    
    
    
    

    


    
        
            
            
        
    



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/964124.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号