java Post 上传文件

package com.ckn.web.main;  
  
import java.io.BufferedReader;  
import java.io.DataInputStream;  
import java.io.File;  
import java.io.FileInputStream;  
import java.io.InputStreamReader;  
import java.io.OutputStream;  
import java.net.HttpURLConnection;  
import java.net.URL;  
  
public class JavaDirectUpload {  
      
    public static void uploadFile(String urlStr, String  formName,String fileName) {  
        try {  
            // 换行符  
            final String newLine = "\r\n";  
            final String boundaryPrefix = "--";  
            // 定义数据分隔线  
            String BOUNDARY = "========7d4a6d158c9";  
            // 服务器的域名  
            URL url = new URL(urlStr);  
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
            // 设置为POST情  
            conn.setRequestMethod("POST");  
            // 发送POST请求必须设置如下两行  
            conn.setDoOutput(true);  
            conn.setDoInput(true);  
  
            // 设置请求头参数  
            conn.setRequestProperty("connection", "Keep-Alive");  
            conn.setRequestProperty("Charsert", "UTF-8");  
            conn.setRequestProperty("Content-Type","multipart/form-data; boundary=" + BOUNDARY);  
            OutputStream out = conn.getOutputStream();  
            // 上传文件  
            File file = new File(fileName);  
            StringBuilder sb = new StringBuilder();  
            sb.append(boundaryPrefix);  
            sb.append(BOUNDARY);  
            sb.append(newLine);  
            // 文件参数,photo参数名可以随意修改  
            sb.append("Content-Disposition: form-data;name=\""+formName+"\";filename=\""+ fileName + "\"" + newLine);  
            sb.append("Content-Type:application/octet-stream");  
            // 参数头设置完以后需要两个换行,然后才是参数内容  
            sb.append(newLine);  
            sb.append(newLine);  
            // 将参数头的数据写入到输出流中  
            out.write(sb.toString().getBytes());  
            // 数据输入流,用于读取文件数据  
            DataInputStream in = new DataInputStream(new FileInputStream(file));  
            byte[] bufferOut = new byte[1024];  
            int bytes = 0;  
            // 每次读1KB数据,并且将文件数据写入到输出流中  
            while ((bytes = in.read(bufferOut)) != -1) {  
                out.write(bufferOut, 0, bytes);  
            }  
            // 最后添加换行  
            out.write(newLine.getBytes());  
            in.close();  
            // 定义最后数据分隔线,即--加上BOUNDARY再加上--。  
            byte[] end_data = (newLine + boundaryPrefix + BOUNDARY  
                    + boundaryPrefix + newLine).getBytes();  
            // 写上结尾标识  
            out.write(end_data);  
            out.flush();  
            out.close();  
              
            //定义BufferedReader输入流来读取URL的响应  
            BufferedReader reader = new BufferedReader(new InputStreamReader(  
            conn.getInputStream()));  
            String line = null;  
            while ((line = reader.readLine()) != null) {  
                System.out.println(line);  
            }  
        } catch (Exception e) {  
            System.out.println("发送POST请求出现异常!" + e);  
            e.printStackTrace();  
        }  
    }  
      
    public static void main(String[] args){  
        String wxUrlStr="https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token=auto_581";  
        String formName="media";  
        String fileFullPath="D:\\Users\\ex-chengyibo600\\Desktop\\TRANSFILE\\newCarLoan\\1447738780798_Jellyfish.jpg";  
        uploadFile(wxUrlStr,formName,fileFullPath);  
    }  
  
}  

 

Java 中,可以使用 HttpURLConnection 类来进行文件上传,以下是一个示例代码: ```java import java.io.*; import java.net.HttpURLConnection; import java.net.URL; public class FileUploader { public static void main(String[] args) throws Exception { String fileUrl = "http://example.com/upload.php"; // 上传地址 String filePath = "path/to/file"; // 文件路径 String fileName = "file.txt"; // 文件名 // 创建连接 URL url = new URL(fileUrl); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setDoOutput(true); connection.setDoInput(true); connection.setRequestMethod("POST"); connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=---------------------------7d6d4f206d0d"); // 构建请求体 OutputStream outputStream = connection.getOutputStream(); PrintWriter writer = new PrintWriter(new OutputStreamWriter(outputStream, "UTF-8"), true); writer.append("-----------------------------7d6d4f206d0d\r\n"); writer.append("Content-Disposition: form-data; name=\"file\"; filename=\"" + fileName + "\"\r\n"); writer.append("Content-Type: application/octet-stream\r\n\r\n"); FileInputStream inputStream = new FileInputStream(filePath); byte[] buffer = new byte[1024]; int bytesRead; while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } outputStream.flush(); inputStream.close(); writer.append("\r\n-----------------------------7d6d4f206d0d--\r\n"); writer.flush(); writer.close(); // 获取响应结果 InputStream responseStream = connection.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(responseStream, "UTF-8")); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } reader.close(); } } ``` 需要注意的是,上述示例中的上传地址和请求体格式需要根据实际情况进行修改。同时,如果要上传多个文件,可以在请求体中添加多个 `Content-Disposition` 字段即可。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值