Vue form post request combined with Servlet to realize file upload function

Vue form post request combined with Servlet to realize file upload function

Front-end test page code:

<template>
 <div>
  <input type="file" name="file" @change="change($event)">
 </div>
</template>
<script>
 export default {
  created(){
   this.path = this.$route.query;
   for (let i in this.path) {
    this[i] = decodeURIComponent(this.path[i]);
   }
  },
  methods:{
   change(ev){
    let file = ev.target.files[0];
    let size = file.size;
    let name = file.name;
    if(size > 314572800){
     this.$message.warning('Uploaded files cannot exceed 300M');
     return;
    }
    let formData = new FormData();
    formData.append('file',file,name)
    this.$axios.post('/JT3'+this.getddRecordDelete,formData,{
     headers:{"Content-Type":"multipart/form-data"}
    }).then(data=>{
     console.log(data);
    })
   }
  }
 }
</script>
<style scoped>
</style>

Backend servlet receiving code

package jt3.control.zygkh;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem; 
import org.apache.commons.fileupload.FileUploadException; 
import org.apache.commons.fileupload.disk.DiskFileItemFactory; 
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import jtacc.filter.JTKit;
import jtacc.jtpub.DT; 
@WebServlet(urlPatterns = "/upfile/file") 
public class UploadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println(11);
		this.doPost(request, response);
 }
 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 	String uri="/u/file/"+DT.getFormatDate("yyyyMMdd")+"/"; //Define the path String tmpPath=JTKit.getBaseDIR()+uri; //This is the personal project path, define the path according to your needs DiskFileItemFactory factory = new DiskFileItemFactory();
		factory.setRepository(new File(tmpPath));//temporary file storage path ServletFileUpload fileUpload = new ServletFileUpload(factory);//core operation object fileUpload.setHeaderEncoding("utf-8");//anti-garbled code try {
			//If you want to force the conversion in real time, you need to download the jar package (commons-fileupload-1.3.3.jar)
			List<FileItem> list = fileUpload.parseRequest(request);
			for (FileItem fileItem : list) {
				InputStream in = fileItem.getInputStream();
				String filename = fileItem.getName();
				if (fileItem != null) {
					System.out.println(filename);
					int len ​​= 0;
					byte[] array = new byte[1024];
					FileOutputStream fos = new FileOutputStream(tmpPath+filename);
					while((len = in.read(array))!=-1){//Indicates that a maximum of 1024 bytes can be read each time fos.write(array,0,len);
						fos.flush();
					}
					fos.close();
					in.close();
					fileItem.delete();
					response.setCharacterEncoding("UTF-8");
					String realPath = uri+filename;
					response.getWriter().append(realPath);
				}
			}
		} catch (FileUploadException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
 }
 
}

Test Results

Supplement: Servlet obtains data submitted by the form

In the Servlet's doPost method:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}

To get the form data, first of all, in order to prevent the problem of Chinese garbled characters, you need to set the encoding of the request to "UTF-8":

request.setCharacterEncoding("utf-8");

How to get a single string:

String username = request.getParameter("username");

How to get string array:

String[] favorites = request.getParameterValues("favorite");

The above is my personal experience. I hope it can give you a reference. I also hope that you will support 123WORDPRESS.COM. If there are any mistakes or incomplete considerations, please feel free to correct me.

You may also be interested in:
  • Vue implements attachment upload function
  • Spring+Vue integrates UEditor rich text to upload picture attachments
  • Two solutions for Vue package upload server refresh 404 problem
  • Vue+element+oss realizes front-end fragment upload and breakpoint resume
  • Based on vue-simple-uploader, encapsulate the global upload plug-in function of file segment upload, instant upload and breakpoint resume
  • Vue uses vue-quill-editor rich text editor and uploads pictures to the server
  • Realize mobile image upload, compression, drag-and-drop sorting, and drag-and-drop deletion functions based on Vue2
  • Things to note when uploading pictures with vue+vant
  • Vue realizes uploading after cropping pictures
  • Implementation example of uploading multiple attachments in Vue

<<:  Example of how to automatically start an application service in a Docker container

>>:  How to modify the initial password of MySQL on MAC

Recommend

Pure CSS to achieve click to expand and read the full text function

Note When developing an article display list inte...

The implementation of Youda's new petite-vue

Table of contents Preface Introduction Live Easy ...

Docker-compose installation db2 database operation

It is troublesome to install the db2 database dir...

vue.js Router nested routes

Preface: Sometimes in a route, the main part is t...

Detailed explanation of MySQL combined query

Using UNION Most SQL queries consist of a single ...

Alibaba Cloud ESC Server Docker Deployment of Single Node Mysql

1. Download the accelerated version of msyql dock...

Pure CSS code to achieve flow and dynamic line effects

Ideas: An outer box sets the background; an inner...

How to create a MySQL master-slave database using Docker on MacOS

1. Pull the MySQL image Get the latest MySQL imag...

React+axios implements github search user function (sample code)

load Request Success Request failed Click cmd and...

WeChat applet realizes the nine-square grid effect

This article shares the specific code for the WeC...

Super detailed teaching on how to upgrade the version of MySQL

Table of contents 1. Introduction 2. Back up the ...

Public free STUN servers

Public free STUN servers When the SIP terminal us...

Understanding of web design layout

<br />A contradiction arises. In small works...

How to create a file system in a Linux partition or logical volume

Preface Learn to create a file system on your sys...