java - 以编程方式在 Android 中的 Php 服务器上上传图像

标签 java php android image-uploading

我正在尝试将图像从 android 上传到 php 服务器服务器正在使用 objective c 为 ios 工作,但在 android 中我不知道如何上传图像。我尝试了以下代码,但服务器返回消息(图像格式不正确或缺少图像文件

        ArrayList<File> imageFiles= new ArrayList<File>();
        for(int i=0;i<mCameraDataList.size();i++) {
           File f = new File(getFilesDir(),"image"+i+".jpg");
            f.createNewFile();
            Bitmap bitmap = Bitmap.createScaledBitmap(
                    BitmapFactory.decodeByteArray(mCameraDataList.get(i), 0, mCameraDataList.get(i).length),CommonMethods.getDeviceWidth(this), CommonMethods.getDeviceHeight(this), true);
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 90, stream);
            byte[] bitmapdata = stream.toByteArray();
            FileOutputStream fos = new FileOutputStream(f);
            fos.write(bitmapdata);
            fos.flush();
            fos.close();
            imageFiles.add(f);
        }

  public static void postProduct(ArrayList<File> nImages) throws UnsupportedEncodingException {
        MultipartEntityBuilder entity=MultipartEntityBuilder.create();
        entity.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        entity.addPart("authenticity",new StringBody("1"));
        entity.addPart("brand_id",new StringBody("1"));
        entity.addPart("cat_id",new StringBody("2"));
        entity.addPart("color_id1",new StringBody("2"));
        entity.addPart("color_id2",new StringBody("3"));
        entity.addPart("condition_id",new StringBody("3"));
        entity.addPart("description",new StringBody("Bgvv"));
        entity.addPart(Constants.KeyValues.DEVICE_ID,new StringBody(Constants.DEVICE_ID));
        entity.addPart("images",new StringBody("images"));
        entity.addPart("lon",new StringBody("74.344630"));
        entity.addPart("lat",new StringBody("31.516762"));
        entity.addPart("name_brand",new StringBody("2 puffs"));
        entity.addPart("package_size",new StringBody("0"));
        entity.addPart("selling_price", new StringBody("20"));
        entity.addPart("title",new StringBody("My test"));
        entity.addPart(Constants.KeyValues.UID,new StringBody(String.valueOf(CommonObjects.getUserProfile().getUid())));
        for(int i=0;i<nImages.size();i++)
        {
            File f=new File(nImages.get(i).getAbsolutePath());
            if(f.exists()){
                entity.addPart(Constants.KeyValues.IMAGES, new FileBody(f, "image/jpeg"));
            }
        }
        new SetDataToServer(Constants.NetworkServiceMethods.Product.POST_PRODUCT, entity, new SetDataToServer.SetDataNotifier() {
            @Override
            public void onDataReceived(boolean isError, String message, JSONObject jsonObj) {
                ArrayList<String> postProductResult =new ArrayList<String>();
                try {
                    Log.e("JSON",jsonObj.toString());
                    if (!jsonObj.isNull(Constants.KeyValues.DATA)) {
                        JSONObject jsonObjectData = jsonObj.getJSONObject(Constants.KeyValues.DATA);
//                        postProductResult.add(jsonObjectData.getString(Constants.KeyValues.CON_ID));
//                        postProductResult.add(jsonObjectData.getString(Constants.KeyValues.ORDER_ID));
                    }
                } catch (JSONException e) {
                    isError = true;
                    message = "Sorry! Error occurred in data parsing";
                }
                productHandlerMethods.onPostProductResult(isError, message, postProductResult);
            }
        }).callServerToSetData();
    }

任何人都可以告诉我做错了什么。

服务端代码

public function postproduct_post() {
        $brand_id = $this->post('brand_id');
        if ($brand_id == '') {
            $brand_name = $this->post('name_brand');
            if ($brand_name == '')
                $this->create_error(-1);
            $brand_id = $this->Mproduct->insertBrandName($brand_name);
        } else {
            if (!$this->Mproduct->_checkBrandId($brand_id))
                $this->create_error(-15, 'brand_id');
        }

        $time = time();
        $uid = $this->post('uid');
        $cat_id = $this->post('cat_id');
        $title = $this->post('title');
        $description = $this->post('description');
        $condition_id = $this->post('condition_id');
        $authenticity = $this->post('authenticity');

        $color_id1 = $this->post('color_id1', 0);
        $color_id2 = $this->post('color_id2', 0);

        $selling_price = $this->post('selling_price');
        $package_size = $this->post('package_size');
        $lat = $this->post('lat');
        $lon = $this->post('lon');

        if ($uid == '' || $cat_id == '' || $title == '' || $description == ''
                || $color_id1 == '' || $condition_id == '' || $authenticity == '') {
            $this->create_error(-1);
        }

        if (!$this->Muser->_checkUid($uid)) 
            $this->create_error(-10);

        if (!$this->Mproduct->_checkCatId($cat_id)) 
            $this->create_error(-15, 'cat_id');

        if ($color_id1 > 0 && !$this->Mproduct->_checkColorId($color_id1)) {
            $this->create_error(-15, 'color_id1');
        }

        if ($color_id2 > 0 && !$this->Mproduct->_checkColorId($color_id2)) {
            $this->create_error(-15, 'color_id2');
        }
        $images = isset($_FILES['images']) ? $_FILES['images'] : null;
        if ($images == null || count($images['name']) <= 0) {
            $this->create_error(-21);
        }

        $this->load->model('Mfile');

        if (!$this->Mfile->checkArrayImage($images)) {
            $this->create_error(-13);
        }

        if (!$this->Mproduct->_checkConditionId($condition_id)) {
            $this->create_error(-15, 'condition_id');
        }

        $params = array();
        $params['owner_id'] = $uid;
        $params['cat_id'] = $cat_id;
        $params['title'] = $title;
        $params['added'] = $time;
        $params['brand_id'] = $brand_id;
        $params['description'] = $description;
        $params['is_sell'] = 1;
        $params['size_id'] = 101;
        $params['is_swap'] = 0;
        $params['is_give'] = 0;
        $params['color_id1'] = $color_id1;
        $params['color_id2'] = $color_id2;
        $params['condition_id'] = $condition_id;
        $params['authenticity'] = $authenticity;
        $params['lat'] = $lat;
        $params['lon'] = $lon;
        $params['last_activity'] = $time;
        $params['last_comment'] = '';
        $params['status'] = 1;

        if ($selling_price != '')
            $params['selling_price'] = $selling_price;
        if ($package_size != '')
            $params['package_size'] = $package_size;

        $product_id = $this->Mproduct->insertProduct($params);
        if ($product_id == -1) {
            $this->create_error(-16);
        }

        $paths = $this->Mfile->saveArrayImage($images, $product_id, $time);
        if (count($paths) <= 0) {
            $this->create_error(-13);
        }

        $params = array();
        $params['image'] = $this->Mfile->createThumbProduct($paths[0]);
        $params['status'] = 1;
        $this->Mproduct->updateAfterInsertProduct($product_id, $params);
        $this->Mproduct->upItemInCat($cat_id);
        $this->Mproduct->upItemInBrand($brand_id);
        $this->Muser->upItemOfUser($uid);

        $this->Mproduct->insertProductImage($product_id, $paths);
        //$this->Mfeed->insertNotifyNewProduct($time, $uid, $product_id);
        //$this->Mpush->createNotiAddProduct($uid, $product_id);
        $uids = $this->Mproduct->getUidsFollowUser($uid);
        $this->load->model('Mnotify');
        $this->Mnotify->createNotifyMany($uids, $product_id, $uid, 7, array('product_id' => $product_id, 'uid' => $uid));
        $this->Mfeed->insertFeedWhenSell($time, $product_id);

        $data = array();
        $data['product_id'] = $product_id;
        $this->create_success($data, 'Add success');        
    }

最佳答案

尝试通过以下用android编写的服务上传图片,确保下面代码中的图片路径正确,将图片放入sdcard:

public class MyService extends Service {
    SharedPreferences sharedPref;
    SharedPreferences.Editor editor;
    int serverResponseCode = 0;
    String upLoadServerUri = null;

    private static final String TAG = "com.example.ServiceExample";

    @Override
    public void onCreate() {
        Log.i(TAG, "Service onCreate");
        sharedPref = getSharedPreferences("myfiles", MODE_PRIVATE);
        /************* Php script path ****************/
        upLoadServerUri = "http://myserver/uploadimage.php";

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        Log.i(TAG, "Service onStartCommand " + startId);

        final int currentId = startId;

        Runnable r = new Runnable() {
            public void run() {

                for (int i = 0; i < 3; i++) {
                    // long endTime = System.currentTimeMillis() + 10*1000;

                    // while (System.currentTimeMillis() < endTime) {
                    synchronized (this) {
                        try {

                            uploadFile(sharedPref.getString(i + "", ""));

                        } catch (Exception e) {
                        }

                    }
                    // }
                    Log.i(TAG, "Service running " + currentId);
                }
                stopSelf();
            }
        };

        Thread t = new Thread(r);
        t.start();
        return Service.START_STICKY;
    }

    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        Log.i(TAG, "Service onBind");
        return null;
    }

    @Override
    public void onDestroy() {
        Log.i(TAG, "Service onDestroy");
    }

    public int uploadFile(String sourceFileUri) {

        String fileName = sourceFileUri;

        HttpURLConnection conn = null;
        DataOutputStream dos = null;
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";
        int bytesRead, bytesAvailable, bufferSize;
        byte[] buffer;
        int maxBufferSize = 1 * 1024 * 1024;
        // File sourceFile = new
        // File(Environment.getExternalStorageDirectory(),sourceFileUri);
        File sourceFile = new File(Environment.getExternalStorageDirectory()
                .getAbsolutePath() + "/" + fileName);
        if (!sourceFile.isFile()) {

            return 0;

        } else {
            try {

                // open a URL connection to the Servlet
                FileInputStream fileInputStream = new FileInputStream(
                        sourceFile);
                URL url = new URL(upLoadServerUri);

                // Open a HTTP connection to the URL
                conn = (HttpURLConnection) url.openConnection();
                conn.setDoInput(true); // Allow Inputs
                conn.setDoOutput(true); // Allow Outputs
                conn.setUseCaches(false); // Don't use a Cached Copy
                conn.setRequestMethod("POST");
                conn.setRequestProperty("Connection", "Keep-Alive");
                conn.setRequestProperty("ENCTYPE", "multipart/form-data");
                conn.setRequestProperty("Content-Type",
                        "multipart/form-data;boundary=" + boundary);
                conn.setRequestProperty("uploaded_file", fileName);

                dos = new DataOutputStream(conn.getOutputStream());

                dos.writeBytes(twoHyphens + boundary + lineEnd);
                // dos.writeBytes("Content-Disposition: form-data; name="uploaded_file";filename=""+ fileName + """
                // + lineEnd);
                dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""
                        + fileName + "\"" + lineEnd);
                dos.writeBytes(lineEnd);

                // create a buffer of maximum size
                bytesAvailable = fileInputStream.available();

                bufferSize = Math.min(bytesAvailable, maxBufferSize);
                buffer = new byte[bufferSize];

                // read file and write it into form...
                bytesRead = fileInputStream.read(buffer, 0, bufferSize);

                while (bytesRead > 0) {

                    dos.write(buffer, 0, bufferSize);
                    bytesAvailable = fileInputStream.available();
                    bufferSize = Math.min(bytesAvailable, maxBufferSize);
                    bytesRead = fileInputStream.read(buffer, 0, bufferSize);

                }

                // send multipart form data necesssary after file data...
                dos.writeBytes(lineEnd);
                dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

                // Responses from the server (code and message)
                serverResponseCode = conn.getResponseCode();
                String serverResponseMessage = conn.getResponseMessage();

                Log.i("uploadFile", "HTTP Response is : "
                        + serverResponseMessage + ": " + serverResponseCode);

                if (serverResponseCode == 200) {

                }

                // close the streams //
                fileInputStream.close();
                dos.flush();
                dos.close();

            } catch (MalformedURLException ex) {

                ex.printStackTrace();

                Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
            } catch (Exception e) {

                e.printStackTrace();

                Log.e("Upload file to server Exception",
                        "Exception : " + e.getMessage(), e);
            }

            return serverResponseCode;

        } // End else block
    }

}

关于java - 以编程方式在 Android 中的 Php 服务器上上传图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29949815/

相关文章:

Java 运行时异常 - 错误的树类型

java - 如何捕获动态指定的异常

java - Android + Parse 从 Query 获取 objectId

android - 调用 FirebaseInstanceId.getToken 的行为

android - 如何在显示某个 fragment 时执行一段代码?

java - 如何在Java中实现多维数组的自定义迭代器?

php - 我可以同时提交两份表格吗?

php - PHP 中的无效代码或消息

php - SQLSTATE[HY000] : General error: 5 Out of memory (Needed 4194092 bytes)

android - 在android中动态生成的TextView下划线