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>\n" +
                              "alert(\"文件類型錯誤,只允許jpg,png,jpeg,gif\");location=\"fileup.html\";\n" +
                              "</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.數據庫

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM