PHP模拟POST上传文件

<?php  
$ch = curl_init();
$path='E:\wamp\www\demo\image\aaa.jpg';
curl_setopt($ch, CURLOPT_HEADER, false);
//启用时会发送一个常规的POST请求,类型为:application/x-www-form-urlencoded,就像表单提交的一样。
curl_setopt($ch, CURLOPT_POST, true);  
curl_setopt($ch,CURLOPT_BINARYTRANSFER,true);
curl_setopt($ch, CURLOPT_POSTFIELDS, ['file' => new CURLFile(realpath($path)), 
]); 
curl_setopt($ch, CURLOPT_URL, 'bcr2.intsig.net/BCRService/BCR_VCF2?user=18910235895@163.com&pass=E34LA7A89EK397RT&json=1&lang=7');
$info= curl_exec($ch);
curl_close($ch);
   
print_r($info);

可以使用 Java 的 HttpURLConnection 类来模拟表单上传文件。以下是一个简单的示例代码: ```java import java.io.*; import java.net.*; public class FileUploader { public static void main(String[] args) throws Exception { String url = "http://example.com/upload.php"; // 上传接口地址 String fileField = "file"; // 表单中文件域的名称 String filePath = "/path/to/file.txt"; // 要上传的文件路径 File file = new File(filePath); URL uploadUrl = new URL(url); HttpURLConnection conn = (HttpURLConnection) uploadUrl.openConnection(); // 设置请求方法POST conn.setRequestMethod("POST"); conn.setDoOutput(true); // 设置请求头 String boundary = "---------------------------" + System.currentTimeMillis(); conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary); // 构造请求体 OutputStream out = conn.getOutputStream(); PrintWriter writer = new PrintWriter(new OutputStreamWriter(out, "UTF-8"), true); writer.append("--" + boundary).append("\r\n"); writer.append("Content-Disposition: form-data; name=\"" + fileField + "\"; filename=\"" + file.getName() + "\"").append("\r\n"); writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(file.getName())).append("\r\n"); writer.append("\r\n"); writer.flush(); FileInputStream inputStream = new FileInputStream(file); byte[] buffer = new byte[4096]; int bytesRead = -1; while ((bytesRead = inputStream.read(buffer)) != -1) { out.write(buffer, 0, bytesRead); } out.flush(); inputStream.close(); writer.append("\r\n").flush(); writer.append("--" + boundary + "--").append("\r\n"); writer.close(); // 发送请求并获取响应 BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream())); String line = null; while ((line = reader.readLine()) != null) { System.out.println(line); } reader.close(); conn.disconnect(); } } ``` 在上面的代码中,我们首先指定了上传接口的地址、表单中文件域的名称和要上传的文件路径。然后构造了一个 URL 对象和 HttpURLConnection 对象,并设置了请求方法和请求头。接着构造了请求体,并将其入输出流中。最后发送请求并获取响应。注意,在请求体中,我们使用了分隔符(boundary)来分隔不同的部分。这个分隔符需要随机生成,且不能与请求体中的其他内容重复。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值