首頁  >  文章  >  Java  >  java如何使用FromData實作檔案上傳(附程式碼)

java如何使用FromData實作檔案上傳(附程式碼)

不言
不言原創
2018-09-25 15:52:554627瀏覽

這篇文章帶給大家的內容是關於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實作檔案上傳(附程式碼)的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn