java实现文件上传(使用FromData)

Posted 飞走的纸飞机

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java实现文件上传(使用FromData)相关的知识,希望对你有一定的参考价值。

一、使用FromData将表单对象序列化后,使用request.getInputStream()来获取数据

1、表单代码如下

<form id="user-info" method="post" action="upload" >
    <input type="file" name="file" multiple> 
    <input type="text" name="username">
    <input type="text" name="password">
</form> 
<button id="sub">提交</button>

2、js的代码

<script>
    function createXHR(){
        return new XMLHttpRequest();
    }
    var sub = document.getElementById("sub");
    sub.onclick=function(){
        var xhr = createXHR();
        var form = document.getElementById("user-info");//获取上边的表单
        xhr.open("post","upload",true);
        xhr.send(new FormData(form));
    }
</script>

 3、由于是序列化的表单所以java后端,不能使用request.getParameter()获取数据,需要使用request.getInputStream();获取数据

首先我们看到获取的数据

  InputStream in = request.getInputStream();
   BufferedReader br = new BufferedReader(new InputStreamReader(in));
   String str = "";
   while((str=br.readLine())!=null){
        System.out.println(str);
   }

 

可以看到读取到这些数据

4、接着使用apache的上传文件框架进行上传

实现效果

以下是代码

package com.wangyang.servlet;

import java.io.File;
import java.io.IOException;
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;

@WebServlet("/upload")
public class Upload extends HttpServlet {
    private static final long serialVersionUID = 1L;
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
         request.setCharacterEncoding("utf-8");
         response.setContentType("text/html;charset=utf-8");
        /*
        InputStream in = request.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        String str = "";
        while((str=br.readLine())!=null){
            System.out.println(str);
        }
        */
        System.out.println("[-------------------------------------------------------]");
        String filepath=request.getServletContext().getRealPath("/")+"upload/";
        File file = new File(filepath);
        if(!file.exists()) {
            file.mkdir();
        }
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        try {
            List<FileItem> items= upload.parseRequest(request);
            for(FileItem item: items) {
                System.out.println(filepath+item.getName());
                if(!item.isFormField()) {
                    item.write(new File(filepath+item.getName()));
                }
                if(item.isFormField()){
                    System.out.println(item.getString());
                    System.out.println(item.getFieldName());
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        response.sendRedirect("index.jsp");
    }
}
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta  charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Insert title here</title>
</head>
<body>
    <form id="user-info" method="post" action="upload" >
        <input type="file" name="file" multiple> 
        <input type="text" name="username">
        <input type="text" name="password">
    </form> 
    <button id="sub">提交</button>
    <script>
        function createXHR(){
            return new XMLHttpRequest();
        }
        var sub = document.getElementById("sub");
        sub.onclick=function(){
            var xhr = createXHR();
            var form = document.getElementById("user-info");
            xhr.open("post","upload",true);
            xhr.send(new FormData(form));
        }
    </script>
</body>
</html>

 

这里没有进行细节上的编程,只是为了说明简单原理 

以上是关于java实现文件上传(使用FromData)的主要内容,如果未能解决你的问题,请参考以下文章

jQueryajax提交fromdata数据

fromData使用方法详解

fromData使用方法详解

前端上传fromdata在.net接口中用啥类型的参数接收?

vue框架实现文件上传功能

ajax表单作为FromData提交时如何删除输入掩码?