欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-04-10 18:39:26
一、使用FromData将表单对象序列化后,使用request.getInputStream()来获取数据 1、表单代码如下 2、js的代码 3、由于是序列化的表单所以java后端,不能使用request.getParameter()获取数据,需要使用request.getInputStream() ......

一、使用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);
   }

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

可以看到读取到这些数据

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

实现效果

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

以下是代码

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>

 

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