安卓中上传图片到PHP服务器里

2020-09-18 15:03:21  阅读 3353 次 评论 0 条


先给出PHP端的代码:

<?php
$base_path = "./upload/0001/"; //建立文件夹
if(!is_dir($base_path)){
    mkdir($base_path,0777,true);
}
$target_path = $base_path . basename ( $_FILES ['attach'] ['name'] );
if (move_uploaded_file ( $_FILES ['attach'] ['tmp_name'], $target_path )) {
	$array = array (
			"status" => true,
			"msg" => $_FILES ['attach'] ['name'] 
	);
	echo json_encode ( $array );
} else {
	$array = array (
			"status" => false,
			"msg" => "There was an error uploading the file, please try again!" . $_FILES ['attach'] ['error'] 
	);
	echo json_encode ( $array );
}

?>

一段html的测试页面,测试完成可以删除了

<html>    
<body>    
<form action="upload.php" method="post"    
enctype="multipart/form-data">    
<label for="file">Filename:</label>    
<input type="file" name="attach" id="file" />     
<br />    
<input type="submit" name="submit" value="Submit" />    
</form>    
</body>    
</html>


再贴出JAVA的代码:

这里面***********部分可以用Fiddle 抓包看看 同时再注意里面的--的数量 

----************

----************

之间就是byte 其他都为字符

关键是拼装起来 

具体修改一下 ds.writeBytes 部分的代码 

protected static String uploadFile(String urlString, String FilePath) {
    /* 上传文件至Server,uploadUrl:接收文件的处理页面 */
    String filename = "";
    int pos = FilePath.lastIndexOf("/");
    if (pos >= 0) {
        filename = FilePath.substring(pos + 1);
    }
    String end = "\r\n";
    String Hyphens = "--";
    String boundary = "----**************";
    //Content-Type: multipart/form-data; boundary=----************
    try {
        URL url = new URL(urlString);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        // 设置每次传输的流大小,可以有效防止手机因为内存不足崩溃
        // 此方法用于在预先不知道内容长度时启用没有进行内部缓冲的 HTTP 请求正文的流。
        //httpURLConnection.setChunkedStreamingMode(128 * 1024);// 128K
        // 允许输入输出流
        conn.setDoInput(true);
        conn.setDoOutput(true);
        conn.setUseCaches(false);
        // 使用POST方法
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Connection", "Keep-Alive");
        conn.setRequestProperty("Charset", "UTF-8");
        conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
        DataOutputStream ds = new DataOutputStream(conn.getOutputStream());
        ds.writeBytes(Hyphens + boundary + end);
        ds.writeBytes("Content-Disposition: form-data; name=\"attach\"; filename=\""
                + filename + "\"" + end);
        ds.writeBytes(end);
        FileInputStream fis = new FileInputStream(FilePath);
        int bufferSize = 1024; //每次写入1024字节
        byte[] buffer = new byte[bufferSize];
        int length = -1;
        // 读取文件
        while ((length = fis.read(buffer)) != -1) {
            ds.write(buffer, 0, length);
        }

        ds.writeBytes(end);
        
        ds.writeBytes(Hyphens + boundary  + end);
        
        ds.writeBytes("Content-Disposition: form-data; name=\"submit\""+ end);
        
        ds.writeBytes(end);
        
        ds.writeBytes("Submit"+end);
        
        ds.writeBytes(Hyphens + boundary + Hyphens + end);
        fis.close();
        ds.flush();
        InputStream is = conn.getInputStream();
        int ch;
        StringBuffer b = new StringBuffer();
        while ((ch = is.read()) != -1) {
            b.append((char) ch);
        }

        ds.close();
        is.close();
        return filename + "上传成功";

    } catch (Exception e) {
        //Toast.makeText(this, e.getMessage().toString(), Toast.LENGTH_LONG).show();
        e.printStackTrace();
        return filename + "上传失败"+e.toString()+"\n"+e.getMessage();

    }

}



在android2.3之后 在主线程中必须使用另一个线程 如duhandler机制,或者异步任务获取网络数据

如果你访问网络的操作 必须放在主线程中执行,那么 在oncreate()中添加


StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()

.detectDiskReads().detectDiskWrites().detectNetwork()

.penaltyLog().build());

StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()

.detectLeakedSqlLiteObjects().penaltyLog().penaltyDeath()

.build());


这样 高版本中也可以在主线程中执行网络操作了

下面发一段改进的代码 上传过程中同时生产缩略图

<?php
function img_create_small($big_img, $width, $height, $small_img) {//原始大图地址,缩略图宽度,高度,缩略图地址
    $imgage = getimagesize($big_img); //得到原始大图片
    switch ($imgage[2]) { // 图像类型判断
    case 1:
    $im = imagecreatefromgif($big_img);
    break;
    case 2:
    $im = imagecreatefromjpeg($big_img);
    break;
    case 3:
    $im = imagecreatefrompng($big_img);
    break;
    }
    $src_W = $imgage[0]; //获取大图片宽度
    $src_H = $imgage[1]; //获取大图片高度
    //按比例调整图像大小
    if ($src_W>=$src_H){
        $height=$height*($src_H/$src_W);
    }
    if ($src_W<=$src_H){
        $width=$width*($src_W/$src_H);
    }
    $tn = imagecreatetruecolor($width, $height); //创建缩略图
    imagecopyresampled($tn, $im, 0, 0, 0, 0, $width, $height, $src_W, $src_H); //复制图像并改变大小
    imagejpeg($tn, $small_img); //输出图像
    }
$base_path = "./upload/"; //存放� ��
if(!is_dir($base_path)){
    mkdir($base_path,0777,true);
}
$tmp1=basename ( $_FILES ['attach'] ['name'] );
$typeid=substr($tmp1,0,strpos($tmp1,"_"))."/";
$base_path =$base_path. $typeid;
if(!is_dir($base_path)){
    mkdir($base_path,0777,true);
}
if(!is_dir($base_path."s/")){
    mkdir($base_path."s/",0777,true);
}
$target_path = $base_path . substr($tmp1,strpos($tmp1,"_")+1); 
$small_path = $base_path ."s/". substr($tmp1,strpos($tmp1,"_")+1); 
if (move_uploaded_file ( $_FILES ['attach'] ['tmp_name'], $target_path )) {
    img_create_small($target_path,300,300,$small_path);
    $array = array (
            "status" => true,
            "msg" => $_FILES ['attach'] ['name'] 
    );
    echo json_encode ( $array );
} else {
    $array = array (
            "status" => false,
            "msg" => "文件上传错误!" . $_FILES ['attach'] ['error'] 
    );
    echo json_encode ( $array );
}

?>


本文地址:https://jinesc.net/?id=195
版权声明:本文为原创文章,版权归 jinesc 所有,欢迎分享本文,转载请保留出处!

发表评论


表情

还没有留言,还不快点抢沙发?