• 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;
        }
    }
  • 相关阅读:
    jQuery
    Android系统内置应用
    最新版小说泛站群系统源码 小说泛目录站群源码系统程序/PHP语言(源码+教程)
    区块链与云计算的融合:新时代数据安全的挑战与机遇
    webScoket长连接人性化解读
    Python|OpenCV-图像的添加和混合操作(8)
    leetcode 146. LRU 缓存
    Win11C盘变红怎么办?Win11C盘变红的清理方法
    芒果改进YOLOv7系列:首发改进特征融合网络BiFPN结构,融合更多有效特征
    java8的一些认识
  • 原文地址:https://blog.csdn.net/weixin_44710155/article/details/126103491