search
HomeWeb Front-endFront-end Q&AWhat to do if vue file upload error occurs

Solution to vue file upload error: 1. Create a vue project through "vue init webpack demo"; 2. Add an element to upload files; 3. Add "upload(data)" to the method Method; 4. Use FromData to add the required parameters, and use axios to submit the request.

What to do if vue file upload error occurs

The operating environment of this tutorial: Windows 10 system, vue3 version, DELL G3 computer

What should I do if there is an error when uploading vue files?

The solution to Vue’s failure to upload files

A colleague who developed the front-end in a project used Vue to develop a Module for uploading files, but it cannot submit this POST request to the background service anyway.
The specific phenomenon is that when the front-end interface uploads files,
Content-Type is always application/x-www-form-urlencoded , and then SpringBoot's background service reports an error: Current is not a multipart request. It means that the request is wrong.

In fact, when the post uploads the file, it should be Content-Type: multipart/form-data, but the front end is inside the intranet and is encapsulated. After analysis and testing, there is no problem uploading a file using ordinary HTML. The problem must lie in the VUE submission request process. Because the real development environment is in the company's intranet environment and is isolated from the outside world, I decided to simulate this scenario on my computer to facilitate problem solving.

In order to realize this simulated environment, you need to install a Vue development environment and a Python development environment. These two development installation methods are not the focus of the article, so they are skipped.

General idea:

Use Vue to develop a simple front-end interface to implement the file upload function, and then use Python to develop a Web back-end service.

Step 1: Create a WEB page with Vue

Create a vue project:

vue init webpack demo

To submit a request using axios, you don’t need to install it. Use Just import it directly

Use VSCode to open the newly created vue project

What to do if vue file upload error occurs

Add an element to upload files:

<template>
  <div>
    <img  src="/static/imghwm/default1.png" data-src="./assets/logo.png" class="lazy" alt="What to do if vue file upload error occurs" >
    <router-view></router-view>
    <input>
  </div>
  
</template>
<script></script>
<script>

import axios from &#39;axios&#39;
export default {
  name: &#39;App&#39;
}
</script>

<style>
#app {
  font-family: &#39;Avenir&#39;, Helvetica, Arial, sans-serif;
  -webkit-font-smoothing: antialiased;
  -moz-osx-font-smoothing: grayscale;
  text-align: center;
  color: #2c3e50;
  margin-top: 60px;
}
</style>

Key points

Then add the control script:

<template>
  <div>
    <img  src="/static/imghwm/default1.png" data-src="./assets/logo.png" class="lazy" alt="What to do if vue file upload error occurs" >
    <router-view></router-view>
    <input>
  </div>
  
</template>
<script></script>
<script>
import axios from &#39;axios&#39;
export default {
  name: &#39;App&#39;,
    methods:{
    upload(data){
          console.log(&#39;--->&#39;,data)         
          var formData = new FormData();
          formData.append(&#39;side&#39;, &#39;front&#39;);
          formData.append(&#39;file&#39;,data.target.files[0]);
          
          let config = {
             headers: {
               &#39;Content-Type&#39;: &#39;multipart/form-data&#39;             
             }
          };
          axios.post(&#39;http://127.0.0.1:5050/icard/check&#39;,formData,config)
            .then((response) => {
                console.log("OK");
          })
        }  
  }
}</script>

Add the upload(data) method to the method
Use FromData to add the required parameters and submit it with axios Just request it.

Step 2: Use Python to develop a simple Web service

from flask import Flask, request
from flask_cors import CORS

app = Flask(__name__)

#跨域处理
cors = CORS(app, supports_credentials=True)

@app.route('/icard/check',methods=['POST'])
def deal_request1():
    print('收到post请求')
    side = request.form["side"]
    image = request.files.get('file')   
      
    print("side= %s"% (side))
    print("filename= %s"% (image.filename))

    return "OK"

if __name__ == '__main__':   
    app.run(host="127.0.0.1", port=5050)

Python's Flask is simply too sharp, and it is so easy to create a simple WEB service.
The basic idea is to create a service on the local port 5050. When there is an HTTP request for the URL http://127.0.0.1:5050/idcard/check, it receives parameters and prints out the received parameters.

After starting in jupyter, the following is as follows:

What to do if vue file upload error occurs

After starting, the prompt: Running on http://127.0.0.1:5050/ (Press CTRL C to quit )

OK, the simple WEB service is started, then start vue,

Open the command line terminal in VSCodel, enter npm run dev to start,

Then Open in the browser https://www.php.cn/link/5ba026c424f718a4808f9d3f75856dab

What to do if vue file upload error occurs

##Because it is the initial project of vue, so after opening it, this is the key point It is the last line to select a file. At this time, open the browser debugging tool first, then select a file and look at the information in the browser debugging tool. The highlight is coming

because a log is added to the vue code Output: console.log('--->',data)

So you can see the log information in the browser

What to do if vue file upload error occurs

The important places are marked with red lines, you can see For the data in the event output here,

you can get the file object that needs to be uploaded according to event.target.file[0], and then look at the situation in the Network:

What to do if vue file upload error occurs

There are two lines of important information in the Request Header:

  Content-Length: 69392
  Content-Type: multipart/form-data; boundary=----WebKitFormBoundarycgFDx4PDNjkXoSnZ

第一行表示上传的文件大小字节数,
Content-Type代表发送端发送的实体数据的数据类型,如果向服务器端发送的是普通的字符串,默认设置为:text/html;
post请求肯定要发送数据包;
因此对数据包的Type有专门的限定:
Content-Type只能是
application/x-www-form-urlencoded,
application/json
multipart/form-data
或 text/plain中的一种。
其他的均不常见。

在看看服务端的情况:

What to do if vue file upload error occurs

Web 服务端立即输出了相关信息,说明已经得到了上传文件的数据,这里为了做测试仅仅输出了文件名和另一个参数。
在我的电脑上测试上传文件,接收文件都OK。
然后同事根据我的代码修改了内网VUE工程的代码,问题来了,在内网里上传文件时也用console.log(data)输出了event,但是格式和这里不同哦,这是很大的疑惑或许是环境问题吧,
在我的测试工程中用event.target.file[0]可以得到需要上传的文件对象,但是在内网环境下event里面根本木有target这个节点,根据最后需要的是file节点的特征,在raw节点下找到了file节点,然后代码修改为
 

upload(data){
          console.log('--->',data)         
          var formData = new FormData();
          formData.append('side', 'front');
          formData.append('file',data.raw.files[0]);
          
          let config = {
            // headers: {
            //   'Content-Type': 'multipart/form-data'             
            // }
          };
          axios.post('http://127.0.0.1:5050/icard/check',formData,config)
            .then((response) => {
                console.log("OK");
          })
        }

内网环境下上传文件成功了。并且测试发现,只要这里正确得到了文件对象参数,那么可以不用显式指定Content-Type,这里也会自动把Content-Type设置为multipart/form-data,我不了解Vue底层是如何处理的,可能是发现提交的数据是流,因此把这里的类型自动设置成了multipart/form-data。

 推荐学习:《vue视频教程

The above is the detailed content of What to do if vue file upload error occurs. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
wpsystem是什么文件夹wpsystem是什么文件夹Sep 01, 2022 am 11:22 AM

wpsystem文件夹是windows应用文件夹;创建WpSystem文件夹是为了存储某些特定“Microsoft Store”应用程序的数据,因此建议不要删该文件夹,因为删除之后就无法使用指定的应用。

winreagent是什么文件夹winreagent是什么文件夹Aug 26, 2022 am 11:23 AM

winreagent是在系统更新或升级的过程中创建的文件夹;该文件夹中通常包含临时文件,当更新或升级失败时,系统将通过还原先前创建的临时文件来回滚到执行更新或升级过程之前的版本。

baidunetdiskdownload是什么文件夹baidunetdiskdownload是什么文件夹Aug 30, 2022 am 10:45 AM

baidunetdiskdownload是百度网盘默认下载文件的文件夹;百度网盘是百度推出的一项云存储服务,只要下载东西到百度网盘里,都会默认保存到这个文件夹中,并且可跨终端随时随地查看和分享。

usmt.ppkg是什么文件usmt.ppkg是什么文件Sep 09, 2022 pm 02:14 PM

“usmt.ppkg”是windows自带的系统还原功能的系统备份文件;Windows系统还原是在不需要重新安装操作系统,也不会破坏数据文件的前提下使系统回到原有的工作状态,PBR恢复功能的备份文件就是“usmt.ppkg”。

mobileemumaster是什么文件mobileemumaster是什么文件Oct 26, 2022 am 11:28 AM

mobileEmuMaster是手机模拟大师的安装文件夹。手机模拟大师是PC电脑模拟运行安卓系统的免费模拟器程序,一款可以让用户在电脑上运行手机应用的软件,支持安装安卓系统中常见的apk执行文件,支持QQ、微信等生活常用应用,达到全面兼容的效果。

kml是什么文件的格式kml是什么文件的格式Sep 14, 2022 am 10:39 AM

kml是谷歌公司创建的一种地标性文件格式;该文件用于记录某一地点或连续地点的时间、经度、纬度、海拔等地理信息数据,可以被“Google Earth”和“Google Maps”识别并显示。

备份文件的扩展名通常是什么备份文件的扩展名通常是什么Sep 01, 2022 pm 03:55 PM

备份文件的扩展名通常是“.bak”;bak文件是一个备份文件,这类文件一般在'.bak前面加上应该有原来的扩展名,有的则是由原文件的后缀名和bak混合而成,在生成了某种类型的文件后,就会自动生成它的备份文件。

config是什么文件夹可以删除吗config是什么文件夹可以删除吗Sep 13, 2022 pm 03:48 PM

config是软件或者系统中的配置文件,不可以删除;该文件是在用户开机时对计算机进行初始化设置,也就是用户对系统的设置都由它来对计算机进行恢复,因此不能删除软件或者系统中的config配置文件,以免造成错误。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft