码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2018-09-23 15:02:30      阅读:385      评论:0      收藏:0      [点我收藏+]

标签:class   getname   mda   init   user   对象序列化   cti   .com   reader   

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

标签:class   getname   mda   init   user   对象序列化   cti   .com   reader   

原文地址:https://www.cnblogs.com/wangyang1749/p/9692507.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!