• HTML5使用Ajax上传文件


    HTML5页面

    1. <form id="uploadForm" enctype="multipart/form-data">
    2. <input id="file" type="file" name="file" multiple="multiple" onchange="selectFile()"/><br>
    3. form>

    JS

    //引入jquery
    
    

    项目需要阿里巴巴的fastjson以便返回json数据

    pom.xml

    
       com.alibaba
       fastjson
       1.2.59
    

    后台代码

    保存路径是

    项目文件\target\classes\static\images\temp

    @PostMapping("upload")
    @ResponseBody
    public JSONObject upload(@RequestParam("file") MultipartFile file){
        JSONObject josn=new JSONObject();
        try {
            String pathA= ResourceUtils.getURL("classpath:").getPath()+"static";
            String detail_path="/images/temp/";
             
        if (file.isEmpty()){
            josn.put("code","error");
            josn.put("message","未选择文件");
            return josn;
        }
        File fileA=new File(pathA); 
        if(!fileA.exists){
             fileA.mkdirs();
       } 
        String filename = file.getOriginalFilename(); //获取上传文件原来的名称
        String filePath = pathA+detail_path;
        System.out.println(filePath);
        File temp = new File(filePath);
        if (!temp.exists()){
            temp.mkdirs();
        }
    
            File localFile = new File(filePath+filename);
            file.transferTo(localFile); //把上传的文件保存至本地
            System.out.println(file.getOriginalFilename()+" 上传成功");
            josn.put("code","sucess");
            //返回文件上传后的目录
            josn.put("message",detail_path+filename);
            return josn;
        }catch (IOException e){
            e.printStackTrace();
            josn.put("code","error");
            josn.put("message","文件上传失败,原因是:"+e.getMessage());
            return josn;
        }
    }
  • 相关阅读:
    2.3.5 交换机的VRRP技术
    【LeetCode】53、 最大子数组和
    【Harbor作为Chart仓库】Helm离线部署AWX1.0.0
    华为AppLinking中统一链接的创建和使用
    2023 Shandong Provincial Collegiate Programming Contest
    jetson xvaier的使用,结合yolo4的感知整合,自动驾驶硬件配置详细过程总结
    Java 8 Stream 的使用场景
    【SimpleDateFormat】线程不安全问题分析及解决方案
    ubuntu 20.04 docker安装emqx 最新版本或指定版本
    2022Q3母婴行业三大热门赛道总结
  • 原文地址:https://blog.csdn.net/weixin_44710155/article/details/126103491