Java HTTP 同时上传两个文件(亲测有效)

Http上传端代码:


import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
 
public class MultiFileUploadExample {
 
    public static void main(String[] args) {
        String urlString = "http://localhost:8009/uploadMore?orderNum=2345678";
        String file1Path = "C:/HWKJ/FTP/20210916/20210916bws.txt";
        String file2Path = "C:/HWKJ/FTP/20210916/20210916xpbws.txt";
 
        try {
            URL url = new URL(urlString);
            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setUseCaches(false);
            connection.setDoOutput(true); // 设置为输出模式
            connection.setRequestMethod("POST");
            connection.setRequestProperty("Connection", "Keep-Alive");
            connection.setRequestProperty("ENCTYPE", "multipart/form-data");
            connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=12345");
 
            // 创建数据输出流
            DataOutputStream dos = new DataOutputStream(connection.getOutputStream());
            // 写入第一个文件数据
            addFormField(dos, "file1", new File(file1Path));
            // 写入第二个文件数据
            addFormField(dos, "file2", new File(file2Path));
 
            // 结束数据发送
            dos.writeBytes("--" + "12345" + "--\r\n");
            dos.flush();
            dos.close();
 
            // 检查响应码
            if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
                System.out.println("文件上传成功");
                // 读取返回数据
                StringBuffer strBuf = new StringBuffer();
                BufferedReader reader = new BufferedReader(new InputStreamReader(
                        connection.getInputStream()));
                String line = null;
                while ((line = reader.readLine()) != null) {
                    strBuf.append(line).append("\n");
                }
                String res  = strBuf.toString();
                System.out.println("响应数据:"+res);
                reader.close();
            } else {
                System.out.println("文件上传失败,响应码:" + connection.getResponseCode());
            }
 
            // 关闭连接
            connection.disconnect();
 
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 
    private static void addFormField(DataOutputStream dos, String fieldName, File uploadFile) throws IOException {
        String boundary = "12345";
        String lineEnd = "\r\n";
        String twoHyphens = "--";
 
        dos.writeBytes(twoHyphens + boundary + lineEnd);
        dos.writeBytes("Content-Disposition: form-data; name=\"" + fieldName + "\"; filename=\""
                + uploadFile.getName() + "\"" + lineEnd);
        dos.writeBytes(lineEnd);
 
        FileInputStream fileInputStream = new FileInputStream(uploadFile);
        BufferedInputStream bufferedInputStream = new BufferedInputStream(fileInputStream);
 
        byte[] buffer = new byte[1024];
        int bytesRead = -1;
        while ((bytesRead = bufferedInputStream.read(buffer)) != -1) {
            dos.write(buffer, 0, bytesRead);
        }
 
        bufferedInputStream.close();
 
        dos.writeBytes(lineEnd);
    }
}

Http接收端代码:

我这里是用springboot作为后台接收端

@PostMapping("/uploadMore")
public String handleFileUpload(
@RequestParam("file1") MultipartFile file1,
@RequestParam("file2") MultipartFile file2,
@RequestParam("orderNum") int orderNum) {
System.out.println("image1:"+file1.getOriginalFilename());
System.out.println("image2:"+file2.getOriginalFilename());
System.out.println("orderNum:"+orderNum);

// 获取文件名
String fileName1 = file1.getOriginalFilename();
String fileName2 = file2.getOriginalFilename();

Date date = new Date();
DateFormat format=new SimpleDateFormat("yyyyMMdd");
String DataForder = format.format(date);

// 设置保存路径,此处为项目根目录下的uploads文件夹
String savePath = "C:/HWKJ/FTP/"+DataForder+ "/" ;

// 文件保存路径
File destFile1 = new File(savePath + fileName1);
File destFile2 = new File(savePath + fileName2);
// 检查文件夹是否存在,不存在则创建
if (!destFile1.getParentFile().exists()) {
destFile1.getParentFile().mkdirs();
}
if (!destFile2.getParentFile().exists()) {
destFile2.getParentFile().mkdirs();
}
// 保存文件
try {
file1.transferTo(destFile1);
file2.transferTo(destFile2);
} catch (IOException e) {
throw new RuntimeException(e);
}

return "文件上传成功" + fileName1+"-"+fileName2;
}

 问题:如果你在上传文件时出现这个错误,说明是你的文件太大,而springboot默认是最大10M

需要在yml文件中配置一下文件大小

  the request was rejected because its size (48012815)

配置内容

spring:
        servlet:
                multipart:
                        max-file-size: 100MB
                        max-request-size: 500MB

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值