java利用HttpURlConnection向指定URL后端传输excel文件

本文介绍了如何使用Java的HttpURLConnection类配合multipart/form-data格式,向SpringBoot后端上传文件的示例,包括创建URL、设置请求头和发送文件内容的过程。
摘要由CSDN通过智能技术生成

如果你正好也需要用java代码而非javascript代码利用URL向后端传输文件,可以参考如下

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

public class FileUploader {
    public static void main(String[] args) throws IOException {
        URL url = new URL("http://localhost:8080/file/upload");
        File file = new File("C:\\Users\\tianyu\\Desktop\\test01.xlsx"); // 指定要上传的文件路径

        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setDoOutput(true);

        String boundary = Long.toHexString(System.currentTimeMillis());
        connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

        try (OutputStream output = connection.getOutputStream();
             FileInputStream fileInput = new FileInputStream(file)) {
            output.write(("--" + boundary + "\r\n").getBytes());
            output.write(("Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + "\"\r\n").getBytes());
            output.write(("Content-Type: application/octet-stream\r\n\r\n").getBytes());

            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = fileInput.read(buffer)) != -1) {
                output.write(buffer, 0, bytesRead);
            }

            output.write(("\r\n--" + boundary + "--\r\n").getBytes());
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }

        int responseCode = connection.getResponseCode();
        System.out.println("Response Code: " + responseCode);

        connection.disconnect();
    }
}

后端用了springboot

 @PostMapping("upload")
    @ResponseBody
    public String upload( MultipartFile file) throws IOException {
        EasyExcel.read(file.getInputStream(), DemoData.class, new PageReadListener<DemoData>(dataList -> {
            for (DemoData demoData : dataList) {
               
                System.out.println(" "+demoData.toString());
            }
        })).sheet().doRead();
        return "success";
    }

效果

解析:

这段代码是一个用Java编写的文件上传示例。它使用HttpURLConnection向指定的URL发送一个POST请求,并将指定的文件作为multipart/form-data格式发送出去。让我来逐步解读这段代码:

首先,创建了一个URL对象,指向要上传文件的目标URL,以及一个File对象,指向要上传的文件。然后,通过url.openConnection()打开一个连接,并强制类型转换为HttpURLConnection

设置url包的基本信息,我们可以看到一个标准的url包,包含了 基本信息、响应头、请求头

       所以先对其进行基本设置,设置请求方法为POST,并设置DoOutput属性为true,表示这个请求是一个输出请求,即它将向服务器发送数据。

生成一个随机的boundary,并设置请求头Content-Typemultipart/form-data; boundary=随机生成的boundary。这个boundary用于分隔不同的部分。

HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setRequestMethod("POST");
        connection.setDoOutput(true);

        String boundary = Long.toHexString(System.currentTimeMillis());
        connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);

       
 

   

通过connection.getOutputStream()获取输出流,然后将文件以multipart/form-data格式写入输出流。这部分代码模拟了一个multipart/form-data格式的请求体,包括了文件的元数据和内容。这一步没做好后台会识别不到文件

代码部分

try (OutputStream output = connection.getOutputStream();
             FileInputStream fileInput = new FileInputStream(file)) {
            output.write(("--" + boundary + "\r\n").getBytes());
            output.write(("Content-Disposition: form-data; name=\"file\"; filename=\"" + file.getName() + "\"\r\n").getBytes());
            output.write(("Content-Type: application/octet-stream\r\n\r\n").getBytes());

            byte[] buffer = new byte[4096];
            int bytesRead;
            while ((bytesRead = fileInput.read(buffer)) != -1) {
                output.write(buffer, 0, bytesRead);
            }

            output.write(("\r\n--" + boundary + "--\r\n").getBytes());
        } catch (IOException ex) {
            throw new RuntimeException(ex);
        }

最后,获取服务器的响应代码,并关闭连接。

总体来说,代码展示了如何使用Java向服务器上传文件。当你执行这段代码时,它会将指定的文件以multipart/form-data格式发送到指定的URL,并输出服务器的响应代码。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值