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

1.HTML页面

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



	
		
		
		
		
		
		
		
		
        
        
		
	
	
		
当前位置:案例管理添加案例
标题
内容
图片

 

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 fileItems = upload.parseRequest(request);
          Iterator 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("");
                      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.数据库

 

 

你可能感兴趣的:(MVVM学习心得,vue,图片上传,formData)