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

Blog    

Recommend

Solution to Docker's failure to release ports

Today I encountered a very strange situation. Aft...

How to handle MySQL numeric type overflow

Now, let me ask you a question. What happens when...

Several situations that cause MySQL to perform a full table scan

Table of contents Case 1: Case 2: Case 3: To summ...

17 404 Pages You'll Want to Experience

How can we say that we should avoid 404? The reas...

A detailed introduction to seata docker high availability deployment

Version 1.4.2 Official Documentation dockerhub st...

How to check PCIe version and speed in Linux

PCIE has four different specifications. Let’s tak...

Specific method to add foreign key constraints in mysql

The operating environment of this tutorial: Windo...

Methods and steps to access Baidu Maps API with JavaScript

Table of contents 1. Baidu Map API Access 2. Usin...

MySQL 5.7.18 free installation version window configuration method

This is my first blog. It’s about when I started ...

Implement a simple search engine based on MySQL

Table of contents Implementing a search engine ba...

Detailed explanation of the use of find_in_set() function in MySQL

First, let’s take an example: There is a type fie...

How to modify the mysql table partitioning program

How to modify the mysql table partitioning progra...

A complete tutorial on using axios encapsulation in vue

Preface Nowadays, in projects, the Axios library ...