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.数据库

 

 

  • 1
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
好的,请问您需要哪方面的帮助呢? 一般来说,vue可以使用axios或者fetch等ajax库发送文件请求,而springboot则可以使用Spring MVC的方式来处理上传文件请求。 上传文件的核心是FormData对象,可以使用它来构造包文件数据的请求体。在vue,我们可以使用如下代码来上传文件: ``` <template> <div> <input type="file" ref="file" @change="handleFileChange"> <button @click="handleUpload">上传</button> </div> </template> <script> import axios from 'axios' export default { methods: { handleFileChange() { // 获取文件对象 this.file = this.$refs.file.files[0] }, handleUpload() { // 构造FormData对象 const formData = new FormData() formData.append('file', this.file) axios.post('/upload', formData, { headers: { 'Content-Type': 'multipart/form-data' } }) .then(response => { // 上传成功,处理回调 }) .catch(error => { // 上传失败,处理错误 }) } } } </script> ``` 在上面的代码,我们使用了input元素的type为file的属性来获取用户选择的文件,然后构造了一个有文件数据FormData对象,并使用axios发送了post请求到服务器的/upload路径。注意需要设置请求头Content-Type为multipart/form-data。 在服务器端,我们可以使用Spring MVC的MultipartFile类型来接收文件。一个简单的springboot上传文件的代码示例: ``` import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; @RestController public class FileController { @PostMapping("/upload") public String upload(@RequestParam("file") MultipartFile file) { try { // 将文件保存到本地 file.transferTo(new File("保存路径")); // 返回上传成功的消息 return "上传成功!"; } catch (IOException e) { // 返回上传失败的消息 return "上传失败!"; } } } ``` 在上面的代码,我们使用了@PostMapping注解来接收POST请求,并使用@RequestParam注解来指定上传文件的参数名称。在方法内部,我们通过调用MultipartFile类型的transferTo方法来将文件保存到本地。注意需要处理文件保存失败的情况,并返回对应的消息。 至于如何将保存的文件回显到前端页面上,可以通过返回上传后的文件路径或者URL,并在前端页面上使用img或video等元素来显示文件。如果需要更加复杂的文件上传、处理、回显等操作,可以使用一些上传组件或者库来辅助完成。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值