上传指定位置文件到指定url服务器

这篇博客介绍了如何使用Java实现将指定位置的文件上传到特定URL。通过设置边界、内容类型和文件名,利用HttpURLConnection进行文件上传操作。文中提供了具体的代码示例,并提到了两种备用的参考资源。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

static String boundary = “abcde12345”;
static String prefix = “–”;
static String newLine = “\r\n”;

public static void test(String serverUrl,String path) {
    try {
        URL url = new URL(serverUrl);
        HttpURLConnection connection = (HttpURLConnection)url.openConnection();
        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setRequestProperty("Content-type", "multipart/form-data;boundary=" + boundary);
        ConfigHttpMultipart(connection.getOutputStream(),path);
        InputStream ins = connection.getInputStream();
        byte[] b = readBuffer(ins);
        System.out.println(new String(b));
    } catch (MalformedURLException e) {
        System.out.println(" url error! ");
    } catch (IOException e) {
        System.out.println(" io error! ");
    }
}

private static void ConfigHttpMultipart(final OutputStream out,String filepath) {
    StringBuffer params = new StringBuffer();

// params.append(prefix + boundary + newLine);
// params.append(“Content-Disposition: form-data; name=“jsonData””);
// params.append(newLine + newLine);
// String jsonData = “{“test”:“test message!”}”;
// params.append(jsonData);
// params.append(newLine);
params.append(prefix + boundary + newLine);
String name=filepath.substring(filepath.lastIndexOf("/")+1,filepath.length());
Log.i(TAG,“name :”+name);
params.append(“Content-Disposition: form-data; name=“file”; filename=”").append(name).append(""");
params.append(newLine);
params.append(“Content-Type: multipart/form-data”);
params.append(newLine + newLine);
File file = new File(filepath);
Log.i(TAG, file.isFile()+", “+ file.exists()+”, “+ file.length()+“filepath :”+filepath);
try {
InputStream in = new FileInputStream(file);
out.write(params.toString().getBytes());
out.write(readBuffer(in));
out.write(newLine.getBytes());
out.write((prefix + boundary + prefix + newLine).getBytes());
out.flush();
out.close();
} catch (FileNotFoundException e) {
System.out.println(” no file! “);
} catch (IOException e) {
System.out.println(” io error! ");
}
}

public static byte[] readBuffer(final InputStream ins) throws IOException {
    byte b[] = new byte[1024];
    ByteArrayOutputStream stream = new ByteArrayOutputStream();
    int len = 0;
    while ((len = ins.read(b)) != -1) {
        stream.write(b, 0, len);
    }
    Log.i(TAG,stream.size()+"");
    return stream.toByteArray();
}

2.https://blog.youkuaiyun.com/u014026084/article/details/73124157

3.https://www.cnblogs.com/lipeineng/p/5731604.html

以上三种方法第一种方法,亲测可用,直接调用过去即可

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值