上傳文件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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM