加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

利用Ajax上传二进制文件

发布时间:2020-12-16 01:42:33 所属栏目:百科 来源:网络整理
导读:网页文件 !doctype html html head meta charset = "utf-8" meta http-equiv = "X-UA-Compatible" content = "IE=edge,chrome=1" meta name = "viewport" content = "width=device-width,initial-scale=1" title 利用Ajax上传二进制文件 / title script type

网页文件

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>利用Ajax上传二进制文件</title>
<script type="text/javascript"> window.onload = function() { var file = null,fileName = null,xhr = null; function upload(url) { var fileInput = document.getElementById("fileInput"); fileInput.addEventListener("change",function() { file = this.files[0]; fileName = file.name; xhr = new XMLHttpRequest(); xhr.open("POST",url); // 这里会自动设置好请求头 xhr.send(file); // 直接上传二进制文件 },false); } var uploadBtn = document.getElementById("upload"); uploadBtn.onclick = function() { upload("/Ajax/FileUploader"); }; }; </script>
</head>
<body>
    <input type="file" id="fileInput" multiple="multiple" />
    <input type="button" id="upload" value="click to upload" />
</body>
</html>

后台简单处理

package cn.chd.fileupload;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/** * Servlet implementation class FileUploader */
public class FileUploader extends HttpServlet {
    private static final long serialVersionUID = 1L;
    int count = 1;

    protected void doGet(HttpServletRequest request,HttpServletResponse response)
            throws ServletException,IOException {
        String path = this.getServletContext().getRealPath("/upload");
        InputStream in = request.getInputStream();
        String contentType = request.getContentType();

        // 这里是为了获取文件扩展名,有点小问题
        String extention = contentType.substring(contentType.indexOf('/') + 1);
        OutputStream out = new FileOutputStream(path + "" + (count++) + "." + extention);
        int len = -1;
        byte[] buffer = new byte[1024];

        while ((len = in.read(buffer)) != -1) {
            out.write(buffer,0,len);
        }

        in.close();
        out.close();
    }

    protected void doPost(HttpServletRequest request,IOException {
        doGet(request,response);
    }

}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读