js 里的 XMLHttpRequest.send(formData) 用 java 中的 HttpURLConnection 怎么写?

function uploadSingleFile(file) {
    var formData = new FormData();
    formData.append("file", file);

    var xhr = new XMLHttpRequest();
    xhr.open("POST", "/uploadFile");

    xhr.onload = function() {
        console.log(xhr.responseText);
        var response = JSON.parse(xhr.responseText);
        if(xhr.status == 200) {
            singleFileUploadError.style.display = "none";
            singleFileUploadSuccess.innerHTML = "<p>File Uploaded Successfully.</p><p>DownloadUrl : <a href='" + response.fileDownloadUri + "' target='_blank'>" + response.fileDownloadUri + "</a></p>";
            singleFileUploadSuccess.style.display = "block";
        } else {
            singleFileUploadSuccess.style.display = "none";
            singleFileUploadError.innerHTML = (response && response.message) || "Some Error Occurred";
        }
    }

    xhr.send(formData);
}
package com.example.filedemo.controller;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

public class HttpMultipart
{
    public static void main(String[] args) throws Exception
    {
        String link = "http://127.0.0.1:8080/uploadFile";
        HttpMultipart hm = new HttpMultipart(link).addParameter("file", new File("G:\\work\\20200819\\servletapi_jb51\\servletapi\\servlet-api.jar")).addParameter("other","somevalue");
        String result = new String(hm.send());
        hm.clearParameter();
        System.out.println(result);

    }

    private URL url;// 链接URL

    private String boundary = "--------" + UUID.randomUUID().toString().replace("-", "");// HTTP报文分隔符

    private Map<String, List<String>> textParams = new HashMap<String, List<String>>();// 字符串表单存储结构

    private Map<String, List<File>> fileParams = new HashMap<String, List<File>>();// 文件表单存储结构

    public HttpMultipart(String url) throws Exception
    {
        this.url = new URL(url);
    }

    protected Map<String, List<File>> getFileParams()
    {
        return fileParams;
    }

    protected Map<String, List<String>> getTextParams()
    {
        return textParams;
    }

    // 增加一个普通字符串数据到form表单数据中
    public HttpMultipart addParameter(String name, String value)
    {
        List<String> list = textParams.get(name);
        if (list == null)
        {
            list = new LinkedList<String>();
            list.add(value);
            textParams.put(name, list);
        }
        else
        {
            list.add(value);
        }
        return this;
    }

    // 增加一个文件到form表单数据中
    public HttpMultipart addParameter(String name, File value)
    {
        List<File> list = fileParams.get(name);
        if (list == null)
        {
            list = new LinkedList<File>();
            list.add(value);
            fileParams.put(name, list);
        }
        else
        {
            list.add(value);
        }
        return this;
    }

    // 删除指定的字符串参数
    public HttpMultipart removeTextParameter(String name)
    {
        textParams.remove(name);
        return this;
    }

    // 删除指定的字符串参数(如果是数组,指定数组下标)
    public HttpMultipart removeTextParameter(String name, int index)
    {
        List<String> list = textParams.get(name);
        if (list != null)
        {
            if (list.size() > index)
            {
                list.remove(index);
            }
            if (list.size() == 0)
            {
                textParams.remove(name);
            }
        }
        return this;
    }

    // 删除指定的文件参数
    public HttpMultipart removeFileParameter(String name)
    {
        fileParams.remove(name);
        return this;
    }

    // 删除指定的文件参数(如果是数组,指定数组下标)
    public HttpMultipart removeFileParameter(String name, int index)
    {
        List<File> list = fileParams.get(name);
        if (list != null)
        {
            if (list.size() > index)
            {
                list.remove(index);
            }
            if (list.size() == 0)
            {
                fileParams.remove(name);
            }
        }
        return this;
    }

    // 清除字符串参数
    public HttpMultipart clearTextParameter()
    {
        textParams.clear();
        return this;
    }

    // 清除文件参数
    public HttpMultipart clearFileParameter()
    {
        fileParams.clear();
        return this;
    }

    // 清除所有参数
    public HttpMultipart clearParameter()
    {
        textParams.clear();
        fileParams.clear();
        return this;
    }

    // 发送数据到服务器,返回一个字节包含服务器的返回结果的数组
    public byte[] send() throws Exception
    {
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();

        long length = getLength();
        connection.setDoOutput(true);
        connection.setUseCaches(false);
        connection.setConnectTimeout(10000); // 连接超时为10秒
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
        connection.setRequestProperty("Content-Length", length + "");
        // connection.setFixedLengthStreamingMode((int) length);//设置上传流大小,防止OutOfMemoryError;但是Int的最大值只支持2G,所以暂时不用;
        connection.setChunkedStreamingMode(65536);// 设置上传流区块大小,防止OutOfMemoryError

        connection.connect();
        OutputStream o = connection.getOutputStream();
        writeFileParams(o);
        writeTextParams(o);
        paramsEnd(o);
        InputStream in = connection.getInputStream();
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        transfer(in, out, 1024);
        out.close();
        in.close();
        connection.disconnect();
        return out.toByteArray();
    }

    // 获取一个字符串表单的长度
    private long getParamLength(String name, String value) throws Exception
    {
        return 49 + boundary.length() + name.length() + value.getBytes().length;
    }

    // 获取一个文件表单的长度
    private long getParamLength(String name, File value) throws Exception
    {
        return 102 + boundary.length() + name.length() + value.getName().getBytes().length + value.length();
    }

    // 获取报文的长度
    private long getLength() throws Exception
    {
        long length = 0;
        for (String name : textParams.keySet())
        {
            List<String> list = textParams.get(name);
            for (String value : list)
            {
                length = length + getParamLength(name, value);
            }
        }
        for (String name : fileParams.keySet())
        {
            List<File> list = fileParams.get(name);
            for (File value : list)
            {
                length = length + getParamLength(name, value);
            }
        }
        length = length + boundary.length() + 8;
        return length;
    }

    // 普通字符串数据
    private void writeTextParams(OutputStream o) throws Exception
    {
        for (String name : textParams.keySet())
        {
            List<String> list = textParams.get(name);
            for (String value : list)
            {
                o.write(new StringBuffer().append("--").append(boundary).append("\r\nContent-Disposition: form-data; name=\"").append(name).append("\"\r\n\r\n").append(value).append("\r\n").toString()
                        .getBytes());
            }
        }
    }

    // 文件数据
    private void writeFileParams(OutputStream o) throws Exception
    {
        for (String name : fileParams.keySet())
        {
            List<File> list = fileParams.get(name);
            for (File value : list)
            {
                o.write(new StringBuffer().append("--").append(boundary).append("\r\nContent-Disposition: form-data; name=\"").append(name).append("\"; filename=\"").append(value.getName())
                        .append("\"\r\nContent-Type: application/octet-stream\r\n\r\n").toString().getBytes());
                writeFile(value, o);
                o.write("\r\n".getBytes());
            }
        }
    }

    // 输出文件
    private void writeFile(File f, OutputStream o) throws Exception
    {
        InputStream in = new FileInputStream(f);
        transfer(in, o);
        in.close();
    }

    // 添加结尾数据
    private void paramsEnd(OutputStream o) throws Exception
    {
        o.write(new StringBuffer().append("--").append(boundary).append("--\r\n\r\n").toString().getBytes());
    }

    // 数据传输
    public static void transfer(InputStream in, OutputStream out) throws Exception
    {
        transfer(in, out, 65536);
    }

    // 数据传输,指定缓冲区大小
    public static void transfer(InputStream in, OutputStream out, int bufSize) throws Exception
    {
        byte[] b = new byte[bufSize];
        int n;
        while ((n = in.read(b)) != -1)
        {
            out.write(b, 0, n);
        }
        b = null;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值