zoukankan      html  css  js  c++  java
  • 上传文件ajax/axios

    文件上传

    1.如何获取HTML属性

    js控制html标签属性和内容
    通过点语法可以访问和设置除了class以外的所有标签属性,这里想设置class属性的话,要使用className来设置,如果想要设置标签中间的内容,那么可以使用innerHTML

    还有getAttribute

    2.获取input的file属性

    单个文件:
    <input id="fileItem" type="file">
    var file = document.getElementById('fileItem').files[0];
    多个文件 查看MDN的file
    

    3.如何将表单 的同步提交变成 异步提交

    前端:

    使用ajax上传:

    <form id="myForm" onsubmit="return false" enctype="multipart/form-data">
            <div>
                <label for="username">Enter name:</label>
                <input type="text" id="username" name="username">
            </div>
            <div>
                <label for="useracc">Enter account number:</label>
                <input type="text" id="useracc" name="useracc">
            </div>
            <div>
                <label for="userfile">Upload file:</label>
                <input type="file" id="userfile" name="file">
            </div>
            <input type="button" value="Submit!" id="submitFile">
        </form>
    
        <script src="jquery-1.12.4.js"></script>
        <script>
            window.onload = function () {
    
    
                $("#submitFile").click(function () {
                    let formData = new FormData($("#myForm")[0]);
                    console.log($("#myForm")[0]);
    
                    formData.append("name", "123");
                    console.log(formData);
                    for (let [a, b] of formData.entries()) {
                        console.log(a, b);
                    }
                    console.log(formData);
                    $.ajax({
                        url: "http://localhost:8080/music3/createSong.do",
                        type: 'post',
                        data: formData,
                        processData: false, //告诉jQuery不要去处理发送的数据
                        contentType: false, //告诉jQuery不要去设置Content-Type请求头
                        success: function (res) {
                            console.log(res);
    
                        }
                    })
    
                });
    
    
    
    
            }
        </script>
    

    使用axios上传

    <template>
        <div class="cancelRequest">
            <div>姓名:<input type="text" v-model="name"></div>
            <div>头像:<input type="file" ref="file"></div>
            <div @click="save">保存</div>
        </div>
    </template>
     
    <script>
    export default {
        data(){
            return {
                value:''
            }
        },
        components:{},
        props:{},
        watch:{},
        computed:{},
        methods:{
            save(){
                let formData=new FormData();
                formData.append('name',this.name)
                formData.append('img',this.$refs.file.files[0])
                this.axios.post('/api/user/query',formData,{
                    'Content-Type':'multipart/form-data'
                }).then(res=>{
     
                })
            }
        },
        created(){},
        mounted(){}
    }
    </script>
    <style>
     
    </style>
     
    
    
    https://blog.csdn.net/weixin_41111068/article/details/81783634
    
    
    
    

    需要:

    /*
    new FormData可以使用ajax发送,用来构造表单的数据;
    */
    var formData = new FormData(form);//form为表单的Dom元素
    
    当我们上传的含有非文本内容,即含有文件(txt、MP3等)的时候,需要将form的enctype设置为multipart/form-data。
    
    在input='file'的标签,通过css样式覆盖了一个label的标签.我们实际看到的这个按钮,其实是一个label标签,通过单击label标签来触发input='file'.从而实现的上传功能.
    
    

    后端:ssm框架

    1.在webapp下创建一个保存文件的文件夹:这里是source文件夹

    2.pox.xml下加入Jar包

    <dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
        <version>2.6</version>
    </dependency>
    <dependency>
        <groupId>commons-fileupload</groupId>
        <artifactId>commons-fileupload</artifactId>
        <version>1.4</version>
    </dependency>
    

    3.在springmvc.xml中加入bean

    在springmvc的配置文件中配置MultipartResolver用于文件上传
    
    <!-- 配置MultipartResolver,用于上传文件 -->
            <bean id = "multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
            <property name="defaultEncoding" value="utf-8"></property>
            </bean>
    

    4.编写Controller

    package com.hstc.controller;
    
    import java.io.FileOutputStream;
    import java.io.InputStream;
    import java.io.OutputStream;
    
    import javax.servlet.http.HttpServletRequest;
    
    import org.apache.commons.io.IOUtils;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.multipart.MultipartFile;
    import org.springframework.web.servlet.ModelAndView;
    
    
    @Controller
    public class UploadController {
    
        @RequestMapping(value = "upload", method = RequestMethod.POST)
        public ModelAndView upload(MultipartFile file, HttpServletRequest request) {
            //获得原来文件的名字
            String oFileName = file.getOriginalFilename();
            System.out.println("文件原来名字叫:" + oFileName);
            //获得原来文件的后缀名
            String ext = oFileName.substring(oFileName.lastIndexOf("."));
            //生成时间戳
            long time = System.currentTimeMillis();
            //生成新的文件名
            String newFileName = time + ext;
            System.out.println("新的文件名字为:" + newFileName);
            
            //获得文件保存的路径
            String dir = request.getServletContext().getRealPath("/source/");
            try {
                //保存文件
                InputStream in = file.getInputStream();
                OutputStream out = new FileOutputStream(dir + "/" + newFileName);
                IOUtils.copy(in, out);
                out.close();
                in.close();
                // 其他处理,比如文件名存数据库,比如把文件名下发
                //把新的文件名存入到数据库中
            } catch (Exception e) {
                e.printStackTrace();
            }
            ModelAndView mav=new ModelAndView();
            mav.setViewName("success");
            mav.addObject("url","upload.jsp");
            mav.addObject("msg","上传成功!");
            return mav;
    
        }
        }
    
    
    

    4.注意:

    1.上传的文件是上传到服务器上,也就是项目发布的tomcat的下的文件夹

    2.注意前后端参数的类型(重点,不然会出现各种问题)

    参考:

    https://blog.csdn.net/sdsjx01/article/details/88394807

    https://www.cnblogs.com/xinchenhui/p/11051368.html

    https://blog.csdn.net/zhizhuodewo6/article/details/79281184(二进制流)

    https://blog.csdn.net/tuesdayma/article/details/78773437

    https://blog.csdn.net/sdsjx01/article/details/88394807(上传)

    https://developer.mozilla.org/zh-CN/docs/Web/API/FileList

  • 相关阅读:
    HTTP 错误 500.19 配置文件错误 ( 0x8007000d,0x80070032)
    system.web下的HttpModules节点和system.webServer下的modules节点的配置区别
    索引超出了数组界限(Microsoft.SqlServer.Smo)
    VS 附加进程调试 Web项目
    VS 调试 无法启动IIS Express Web 服务器(进程不存在)
    java基础面试题
    给dubbo接口添加白名单——dubbo Filter的使用
    mysql行转列转换
    Spring透过ApplicationListener来触发contextrefreshedevent事件
    spring mvc之请求过程源码分析
  • 原文地址:https://www.cnblogs.com/listenMao/p/12833579.html
Copyright © 2011-2022 走看看