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

springmvc-文件上传

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

springmvc-文件上传

1. 文件上传的原理

2. 文件上传到本地服务器

(1)导入文件上传的jar包-commons-fileupload

  
      commons-fileupload
      commons-fileupload
      1.4
    

(2) 创建jsp页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    Title


    
    

(3)在springmvc.xml中配置文件上传解析器


        
    

(4)创建upload01接口方法

@Controller
public class UploadController {
    @RequestMapping("/upload")
    public String upload(MultipartFile myfile, HttpServletRequest request) throws Exception{
        String path = request.getSession().getServletContext().getRealPath("upload");
        System.out.println(path); //上传文件的本地路径
         //新建文件夹
        File file=new File(path);
        //检测。如果文件不存在,将会创建一个文件
        if(!file.exists()){
            file.mkdirs();
        }
           //生成随机的字符串
           //replace:替换
        String fileName = UUID.randomUUID().toString().replace("-","")+myfile.getOriginalFilename();
        File target = new File(path+"/"+fileName);
        myfile.transferTo(target);
        return "";
    }

}
3. elementui+vue+axios完成文件上传

(1)页面的布局

<%--
  Created by IntelliJ IDEA.
  User: xu
  Date: 2022/6/9
  Time: 18:56
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>


    Title
    
    
    
    
    


    
        
            
            
        
    

    

(2)后端的页面

@RequestMapping("/upload02")
    //输出JSon格式
    @ResponseBody
    //MultipartFile file:前端页面默认的name为file
    public Map upload02(MultipartFile file, HttpServletRequest request){
        try {
            String path = request.getSession().getServletContext().getRealPath("upload");
            File file1=new File(path);
            if(!file1.exists()){
                file1.mkdirs();
            }
            String fileName=UUID.randomUUID().toString().replace("-","")
                    +file.getOriginalFilename();
            File target = new File(path+"/"+fileName);
            file.transferTo(target);
            Map map=new HashMap();
            map.put("code",2000);
            map.put("msg","上传成功");
            //路径为服务器的路径
            map.put("data","http://localhost:8080/upload/"+fileName);
            return map;
        } catch (IOException e) {
            e.printStackTrace();
        }
        Map map=new HashMap();
        map.put("code",5000);
        map.put("msg","上传失败");
        return map;
    }

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

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

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