Vue+axios+Servlet 中提交表单数据(含上传图片)超详版!!!

Posted zuojiachen

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Vue+axios+Servlet 中提交表单数据(含上传图片)超详版!!!相关的知识,希望对你有一定的参考价值。

1.html页面

这里用post方法传送,大小不受限制;还用了v-model的双向绑定

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8" />
		<title></title>
		<link href="../css/bootstrap.css" type="text/css" rel="stylesheet">
		<link rel="stylesheet" href="../css/component.css">
		<link rel="stylesheet" href="../css/admin.css">
		<link rel="stylesheet" href="../css/font-awesome.min.css">
		<link rel="stylesheet" href="../css/bootstrap.css">
		<script type="text/javascript" src="../js/vue.js"></script>
        <script type="text/javascript" src="../js/axios.min.js"></script>
        <script src="https://code.jquery.com/jquery-3.4.1.min.js"></script>
		<style>
			.tablestyle{
				padding: 20px;
				width: 400px;
				
			}
			.tablestyle th{
				text-align:left;
			}
			.tablestyle td{
				text-align:left;
			}
		</style>
	</head>
	<body>
		<div class="rbody" id="app">
		<div class="top">
		            当前位置:案例管理<i class="fa fa-fw fa-angle-right"></i>添加案例
		</div>
		</div>
		<div class="tablestyle">
		<form action="" method="post" enctype="multipart/form-data">
			<table border="1px" style="border-collapse: collapse" class="table table-bordered">
				<tr>
					<td>标题</td>
					<td>
						<input type="text" class="form-control" id="tsutitle" placeholder="标题" v-model="tstitle">
					</td>
				</tr>
				<tr>
					<td>内容</td>
					<td>
						<textarea class="form-control" rows="6" placeholder="请输入内容" v-model="tscontent"></textarea>
					</td>
				</tr>
				<tr>
					<td>图片</td>
					<td>
						<input type="file" name="logoImage" @change="getFile($event)"/>
					</td>
				</tr>
				<tr>
					<td align="center">
						<input class="btn btn-default" type="submit" value="提交" @click="submitForm($event)"/>
					</td>
					<td align="left">
						<input class="btn btn-default" type="reset" value="重置" @click="cz();"/>
					</td>
				</tr>
			</table>
		</form>	
		</div>
	<script>
		var add=new Vue({
			el:‘.tablestyle‘,//作用域
			data:{
				tstitle:‘‘,//数据
				tscontent:‘‘,
				file:‘‘
			},
			methods:{
				cz:function(){
					add.tstitle="";
					add.tscontent="";
				},
				getFile(event) {
					this.file = event.target.files[0];
                    //console.log(this.file);
                    alert("上传");
                },
                submitForm(event) {
                	//event.preventDefault();
                	
                	let formData = new FormData();
                    formData.append(‘tstitle‘, this.tstitle);
                    formData.append(‘tscontent‘, this.tscontent);
                    formData.append(‘file‘, this.file);
            
                    let config = {
                            headers: {
                              ‘Content-Type‘: ‘multipart/form-data‘
                            }
                        };
                    //servlet名字为uploadfile   
                    axios.post("../uploadfile",formData,config).then((res)=>{
                    	alert("添加成功!");	
                        // success callback
                    }).catch((err)=>{
                    	alert("添加失败!");
                    });                                                       
			    }               
			}
		});
		
		</script>					
	</body>	
</html>

2.Servlet

package com.web.admin;
 
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.Iterator;
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 com.service.admin.AdminTsuService;
 
/**
 * Servlet implementation class Uploadfile
 */
@WebServlet("/uploadfile")
public class Uploadfile extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Uploadfile() {
        super();
        // TODO Auto-generated constructor stub
    }
 
    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        //response.getWriter().append("Served at: ").append(request.getContextPath());
 
 
    }
 
    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
      // TODO Auto-generated method stub
      doGet(request, response);
      //设置编码方式
      request.setCharacterEncoding("utf-8");
      response.setCharacterEncoding("gb2312");
      
      
      //设置输出
      PrintWriter outprint = response.getWriter();
      //Enumeration files = multipartRequest.getFileNames();
      //设置文件目录
      String webroot = this.getServletContext().getRealPath("/");
      File temppath = new File(webroot + "fileuploadtemp");
      String dir = webroot+ File.separator + "upload";
      File path = new File(webroot+ File.separator + "upload");
      if (!temppath.exists()) {
          temppath.mkdirs();
      }
      if (!path.exists()) {
          path.mkdirs();
      }
 
      //设置文件类型(可加)
      String[] type= new String[]{".jpg",".png",".jpeg",".gif",".bmp"};
 
      //创建文件项工厂
      DiskFileItemFactory factory = new DiskFileItemFactory(1024 * 1024,temppath);
      ServletFileUpload upload = new ServletFileUpload(factory);
      upload.setFileSizeMax(1024 * 1024 * 10);
      try {
          List<FileItem> fileItems = upload.parseRequest(request);
          Iterator<FileItem> it = fileItems.iterator();
          String newFimeName=null;
          String tstitle1=null;
          String tscontent1=null;
          //String tstitle2=null;
          //String tscontent2=null;
          //String name1 = "tstitle";
          //String content1 = "tscontent";
          // int count = 0;
 
          //遍历request file
          while (it.hasNext()) {
              FileItem fi = it.next();
              
              //判断该表单是否为普通表单类型
              if (fi.isFormField()) {
                  String nameString = fi.getFieldName();
                  switch(nameString)
                  {
                     case "tstitle" :
                        //解决转换字节流乱码问题
                        tstitle1 =  new String(fi.getString().getBytes("ISO8859_1"),"utf-8");
                        
                        System.out.println(tstitle1); 
                        break;
                     case "tscontent" :
                         tscontent1 =  new String(fi.getString().getBytes("ISO8859_1"),"utf-8");
                         System.out.println(tscontent1); 
                         break; 
                     default :
                        System.out.println("未知等级");
                  
                }
                  
                  //System.out.println("----"+nameString+"-------");
                  //System.out.println("----"+conString+"-------"); 
              } else {
                  InputStream in = fi.getInputStream();
                  String name = fi.getName();//获得文件原名
 
                  //得到文件后缀名
                  int index = name.lastIndexOf(".");
                  String endWith = name.substring(index);
 
                  //判断是否符合类型
                  boolean TypeExists = Arrays.asList(type).contains(endWith);
                  if (!TypeExists) {
                      outprint.print("<script>
" +
                              "alert("文件类型错误,只允许jpg,png,jpeg,gif");location="fileup.html";
" +
                              "</script>");
                      return;
                      }
 
                      newFimeName = System.currentTimeMillis() + endWith;//新文件名
 
                      //创建上传文件
                      FileOutputStream out = new FileOutputStream(new File(
                              dir + "/" + newFimeName));
 
                      byte buffer[] = new byte[1024];
                      int len = 0;
                      while ((len = in.read(buffer)) > 0) {
                          out.write(buffer, 0, len);//写入大小
                      }
                      
                      in.close();
                      out.close();
                      fi.delete();
                      
                    //  outprint.print("上传成功");
                  }
              }
          
          AdminTsuService tsuService = new AdminTsuService();
          String tsu=tsuService.addone(tstitle1, tscontent1,newFimeName);//调用service层方法
          outprint.println(tsu);
          outprint.flush();//清除缓冲区的数据
          outprint.close();//关闭流     
          } catch(FileUploadException e){
              response.getWriter().write(e.toString());
          }
    }
}

3.service层

    public String addone(String tstitle,String tscontent,String tspicture) {
        int add=tsu.addone(tstitle, tscontent,tspicture);
        return JSON.toJSON(add).toString();
    }

4.dao层

    public int addone(String tstitle,String tscontent,String tspicture) {        
        String sql="insert into tsu(tstitle,tscontent,tspicture) values (?,?,?)";
        int i = DH.update(sql, new String[] {tstitle,tscontent,tspicture});
        return i;
    }

5.数据库

技术图片

 

以上是关于Vue+axios+Servlet 中提交表单数据(含上传图片)超详版!!!的主要内容,如果未能解决你的问题,请参考以下文章

axios表单提交--vue.js

axios异步提交表单数据的不同形式

使用 Vue.js 和 Axios 向 Mailchimp 提交表单会导致 CORS 错误

vue提交表单后清空

无法提交 Axios Post 表单 Nuxt.js (VueJS)

Laravel 和 axios 提交后清除表单