Java 上传到服务器后,图像文件为空

Java 上传到服务器后,图像文件为空,java,php,android,laravel,Java,Php,Android,Laravel,我正在尝试将图像上载到服务器 以下是我在Android中编写的代码,用于将图像文件以及其他一些参数发送到服务器: static String imagePath = "/storage/sdcard0/Pictures/image.jpg"; static String url = "http://example.com/api"; static String user_id = "99401"; public static void executeMultipartPost() throws

我正在尝试将图像上载到服务器

以下是我在Android中编写的代码,用于将图像文件以及其他一些参数发送到服务器:

static String imagePath = "/storage/sdcard0/Pictures/image.jpg";
static String url = "http://example.com/api";
static String user_id = "99401";

public static void executeMultipartPost() throws IOException, ClientProtocolException {

    HttpClient httpclient = new DefaultHttpClient();
    httpclient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);

    HttpPost httppost = new HttpPost(url);
    File file = new File(imagePath);
    FileBody fb = new FileBody(file);

    MultipartEntityBuilder builder = MultipartEntityBuilder.create();
    builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

    builder.addPart("user_id", new StringBody(user_id));
    builder.addPart("type", new StringBody("single"));
    builder.addPart("userfile", fb);
    final HttpEntity entity = builder.build();


    httppost.setEntity(entity);

    Log.i(TAG, "Executing request: " + httppost.getRequestLine());

    HttpResponse response = httpclient.execute(httppost);
    HttpEntity resEntity = response.getEntity();
    Log.i(TAG, ""+response.getStatusLine());
    if (resEntity != null) {
        Log.i(TAG, EntityUtils.toString(resEntity));
    }
    if (resEntity != null) {
        resEntity.consumeContent();
    }
    httpclient.getConnectionManager().shutdown();
}
一切正常,除了上传到服务器时,服务器收到一个空的图像。我只能看到一个0字节的图像文件。我猜客户端代码中的某些内容设置不正确

执行代码后,我在Logcat中得到的响应如下(来自Laravel错误日志):

未处理的异常
信息:
copy():copy()函数的第一个参数不能是目录
地点:
/home/ked.ai/www/laravel/file.php,第92行
堆栈跟踪:
#0/home/ked.ai/www/laravel/laravel.php(42):laravel\Error::native(2,'copy():fir…','/home/ked.ai/ww…',92)
#1[内部函数]:Laravel\{closure}(2,'copy():fir…','/home/ked.ai/ww…',92,数组)
#2/home/ked.ai/www/laravel/file.php(92):复制(“/”,“/home/ked.ai/ww…)
#3/home/ked.ai/www/application/controllers/api2/item.php(190):Laravel\File::copy(“/”,“/home/ked.ai/ww…”)
#4[内部功能]:Api2\u项目\u控制器->发布\u新()
#5/home/ked.ai/www/laravel/routing/controller.php(325):调用用户函数数组(数组,数组)
#6/home/ked.ai/www/laravel/routing/controller.php(285):laravel\routing\controller->response('new',Array)
#7/home/ked.ai/www/laravel/routing/controller.php(165):laravel\routing\controller->execute('new',Array)
#8/home/ked.ai/www/laravel/routing/route.php(153):laravel\routing\Controller::call('api2。item@new,数组)
#9/home/ked.ai/www/laravel/routing/route.php(124):laravel\routing\route->response()
#10/home/ked.ai/www/laravel/laravel.php(167):laravel\Routing\Route->call()
#11/home/ked.ai/www/public/index.php(34):require('/home/ked.ai/ww…'))
#12{main}

它似乎传递的是一个目录而不是一个文件。任何解决方法?

您可以使用此方法将图像传递到php服务器

  • 使用base64.encodeBytes(byte_数据)将图像转换为base64字符串
  • 在服务器端php代码中,通过base64_解码(str)将该base64字符串转换为图像
  • 其工作守则:


    试试看。

    我已经找到了解决办法

    我只需要换这一行

    因为在服务器端,
    $\u FILES['userfile']
    接收数组类型


    谢谢。

    使用FTP将图像上载到serverNo。Laravel是服务器部分。对不起,误会了。我只想使用API url从android设备提交我的图像。我面临着同样的问题。我的问题是,当我将图像编码为base 64并发送到服务器usin时,它会显示灰色图像,但当我将相同的base 64字符串编码并转换为位图时,使用图像中的位图,它会完美地显示图像。我想不出是什么问题,你能帮我吗?还是一样。服务器端使用
    $\u FILE['userfile']
    从客户端获取
    userfile
    参数。通过电话发送有什么问题。Hm.服务器使用
    $\u file
    获取文件。那么您认为有必要将图像转换为base64吗?此外,我不是后端工程师,因此我没有编辑它的权限:(是的,图像路径是正确的。如果我将
    文件://
    附加到路径,则无法找到它。然后使用此.file image=新文件(Environment.getExternalStorageDirectory().getPath().toString()+“/DCIM/camera/image.jpg”);
    <html><h2>Unhandled Exception</h2>
        <h3>Message:</h3>
        <pre>copy(): The first argument to copy() function cannot be a directory</pre>
        <h3>Location:</h3>
        <pre>/home/ked.ai/www/laravel/file.php on line 92</pre>
        <h3>Stack Trace:</h3>
        <pre>#0 /home/ked.ai/www/laravel/laravel.php(42): Laravel\Error::native(2, 'copy(): The fir...', '/home/ked.ai/ww...', 92)
        #1 [internal function]: Laravel\{closure}(2, 'copy(): The fir...', '/home/ked.ai/ww...', 92, Array)
        #2 /home/ked.ai/www/laravel/file.php(92): copy('/', '/home/ked.ai/ww...')
        #3 /home/ked.ai/www/application/controllers/api2/item.php(190): Laravel\File::copy('/', '/home/ked.ai/ww...')
        #4 [internal function]: Api2_Item_Controller->post_new()
        #5 /home/ked.ai/www/laravel/routing/controller.php(325): call_user_func_array(Array, Array)
        #6 /home/ked.ai/www/laravel/routing/controller.php(285): Laravel\Routing\Controller->response('new', Array)
        #7 /home/ked.ai/www/laravel/routing/controller.php(165): Laravel\Routing\Controller->execute('new', Array)
        #8 /home/ked.ai/www/laravel/routing/route.php(153): Laravel\Routing\Controller::call('api2.item@new', Array)
        #9 /home/ked.ai/www/laravel/routing/route.php(124): Laravel\Routing\Route->response()
        #10 /home/ked.ai/www/laravel/laravel.php(167): Laravel\Routing\Route->call()
        #11 /home/ked.ai/www/public/index.php(34): require('/home/ked.ai/ww...')
        #12 {main}</pre></html>
    
    public void executeMultipartPost() throws Exception {
    
            try {
                ByteArrayOutputStream bos = new ByteArrayOutputStream();
                bm.compress(CompressFormat.JPEG, 75, bos);
                byte[] data = bos.toByteArray();
                HttpClient httpClient = new DefaultHttpClient();
                HttpPost postRequest = new HttpPost(url_path);
                ByteArrayBody bab = new ByteArrayBody(data, "forest.jpg");
                // File file= new File("/mnt/sdcard/forest.png");
                // FileBody bin = new FileBody(file);
                MultipartEntity reqEntity = new MultipartEntity(
                        HttpMultipartMode.BROWSER_COMPATIBLE);
    
                reqEntity.addPart("file", bab);
                reqEntity.addPart("category ", new StringBody("1"));
                reqEntity.addPart("user_id ", new StringBody("55"));
    
                postRequest.setEntity(reqEntity);
    
                HttpResponse response = httpClient.execute(postRequest);
    
                String my_response = convertStreamToString(response.getEntity()
                        .getContent());
                Toast.makeText(getApplicationContext(), my_response,
                        Toast.LENGTH_LONG).show();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    
    public static String convertStreamToString(InputStream is) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            StringBuilder sb = new StringBuilder();
    
            String line = null;
            try {
                while ((line = reader.readLine()) != null) {
                    sb.append(line + "\n");
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            return sb.toString();
        }
    
    builder.addPart("userfile", fb);
    
    builder.addPart("userfile[]", fb);