[javaSE] java上传图片给PHP

java通过http协议上传图片给php文件,对安卓上传图片给php接口的理解

java文件:

复制代码
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;


public class HttpUpload {
    public static final String API="http://localhost/test.php";
    public static void main(String[] args) throws Exception {
        String imgUrl="E:\\11.png";
        String result=uploadImg(imgUrl);
        System.out.println(result);
    }

    private static String uploadImg(String imgUrl) throws Exception {
        File imgFile=new File(imgUrl);
        URL url=new URL(API);
        HttpURLConnection conn=(HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(10000);
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Content-Type", "multipart/form-data; boundary=----123456789");
        conn.setDoInput(true);
        conn.setDoOutput(true);
        
        OutputStream os=new DataOutputStream(conn.getOutputStream());
        StringBuilder body=new StringBuilder();
        body.append("------123456789\r\n");
        body.append("Content-Disposition: form-data; name='img'; filename='"+imgFile.getName()+"'\r\n");
        body.append("Content-Type: image/jpeg\r\n\r\n");
        os.write(body.toString().getBytes());
        
        InputStream is=new FileInputStream(imgFile);
        byte[] b=new byte[1024];
        int len=0;
        while((len=is.read(b))!=-1){
            os.write(b,0,len);
        }
        String end="\r\n------123456789--";
        os.write(end.getBytes());
        
        //输出返回结果
        InputStream input=conn.getInputStream();
        byte[] res=new byte[1024];
        int resLen=input.read(res);
        return new String(res,0,resLen);
    }
}
复制代码

PHP文件

复制代码
<?php
class Test{
    public static function main(){
        header("content-type:text/html;charset=utf-8");
        if(!empty($_FILES)){
            $test=new Test();
            $test->uploadImg();
            exit;
        }
    }
    /**
    * 上传图片
    */
    public function uploadImg(){
        $res=move_uploaded_file($_FILES['img']['tmp_name'], './'.$_FILES['img']['name']);
        if($res){
            echo "upload success";
        }else{
            echo "upload error";
        }
    }
}
Test::main();
?>
<form enctype="multipart/form-data" action="test.php" method="post">
<input type="file" name="img" />
<input type="submit" value="上传" />
</form>
复制代码

 

posted @   唯一客服系统开发笔记  阅读(1554)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示
1
chat with us