前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >[javaSE] java上传图片给PHP

[javaSE] java上传图片给PHP

作者头像
唯一Chat
发布2019-09-10 16:37:22
2.5K0
发布2019-09-10 16:37:22
举报

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>
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2016-07-30 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档