1. Introduction
Two days ago, in the company’s requirements, the scene of uploading files appeared again. However, as I have ten years of code experience and always feel the need for something, I immediately gave a very mature solution, using AXIos +FormData to upload.
2. Brief introduction
2.1 axios
Axios, without further ado, is a wrapper around XMLHttpRequest, but of course it also Bridges HTTP from NodeJS, which we won’t expand here. See the AxISO Orthodox website for details.
2.2 FormData
Now, this is a mysterious property, and the main thing is that we usually send requests in json or get params, so I don’t know much about this, but what this constructor actually does is it builds a key/value object like a form that can be sent by XMLHttpRequest, So of course it can store Blob objects as well. When we send data of Blob Type, the Content-Type is set to multipart/form-data, which is then automatically processed, and this is how the file is uploaded.
3. Simple upload
3.1 the front
Here is a simple demonstration of the front-end code, for details, please refer to gitee.com/Agrement/te… :
<template>
<input ref="inputRef" type="file">
<button @click="upload">upload</button>
</template>
<script lang="ts">
import axios from 'axios'
import { defineComponent, ref } from 'vue'
import HelloWorld from './components/HelloWorld.vue'
export default defineComponent({
name: 'App'.components: {
HelloWorld
},
setup(){
const inputRef = ref<HTMLInputElement>();
// funcs
function upload(){
const formdata = new FormData();
constfile =inputRef.value? .files? .item(0);
formdata.append('file', file!) ; axios.post("https://localhost:44335/WeatherForecast",formdata,{headers: {}})}return {
upload,
inputRef
}
}
})
</script>
Copy the code
When I select the file and click Upload, the file is automatically processed and sent:
3.1 the back-end
Here I use.net Core, version 5, and use a breakpoint to check if the receive was successful:
code
[HttpPost()]
public string Post([FromForm] Microsoft.AspNetCore.Http.IFormFile file) {
return ' ';
}
Copy the code
The debugger rendering
4. To summarize
It can be seen that a simple upload can be realized through Axios +HTML5 FormData. Of course, uploading is not only these operations, but also needs to pause, continue uploading, display uploading progress and other requirements in ordinary business. Interested partners can pay attention to my subsequent articles. `