Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/234.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何从android设备上传位图图像?_Java_Android_Http_Multipartform Data - Fatal编程技术网

Java 如何从android设备上传位图图像?

Java 如何从android设备上传位图图像?,java,android,http,multipartform-data,Java,Android,Http,Multipartform Data,先谢谢你。 我想从我的android应用程序上传一些位图图像。 但是,我不明白。 你能推荐一些解决方案吗。 还是收集我的源代码 ByteArrayOutputStream bao = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG, 90, bao); HttpClient httpclient = new DefaultHttpClie

先谢谢你。 我想从我的android应用程序上传一些位图图像。 但是,我不明白。 你能推荐一些解决方案吗。 还是收集我的源代码

ByteArrayOutputStream bao = new ByteArrayOutputStream();
                bitmap.compress(Bitmap.CompressFormat.JPEG, 90, bao);
                HttpClient httpclient = new DefaultHttpClient();
                HttpPost httppost = new HttpPost(
                        "http://example.com/imagestore/post");
                MultipartEntity entity = new MultipartEntity( HttpMultipartMode.BROWSER_COMPATIBLE );
                byte [] ba = bao.toByteArray();
                try {
                    entity.addPart("img", new StringBody(new String(bao.toByteArray())));
                    httppost.setEntity(entity);
                } catch (UnsupportedEncodingException e1) {
                    // TODO Auto-generated catch block
                    e1.printStackTrace();
                }
                // Execute HTTP Post Request
                HttpResponse response = null;
                try {
                    response = httpclient.execute(httppost);
                } catch (ClientProtocolException e) {
}

使用httpime上传图像
试试这个

我发现这个解决方案创建得非常好,而且100%可以与amazon ec2一起使用,请查看以下链接:

与前面的答案相比,此解决方案不需要从Apache导入庞大的库
httpmime

从原始文章复制的文本:

本教程展示了使用Android SDK将数据(图像、MP3、文本文件等)上传到HTTP/PHP服务器的简单方法

它包括在Android端进行上传所需的所有代码,以及一个简单的PHP服务器端代码,用于处理文件上传和保存。此外,它还提供了如何在上载文件时处理基本自动化的信息

在emulator上测试时,请记住通过DDMS或命令行将测试文件添加到Android的文件系统中

我们要做的是设置请求的适当内容类型,并将字节数组作为帖子的主体。字节数组将包含我们要发送到服务器的文件的内容

在下面,您将找到执行上载操作的有用代码段。代码还包括服务器响应处理

HttpURLConnection connection = null;
DataOutputStream outputStream = null;
DataInputStream inputStream = null;
String pathToOurFile = "/data/file_to_send.mp3";
String urlServer = "http://192.168.1.1/handle_upload.php";
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary =  "*****";

int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1*1024*1024;

try
{
    FileInputStream fileInputStream = new FileInputStream(new File(pathToOurFile) );

    URL url = new URL(urlServer);
    connection = (HttpURLConnection) url.openConnection();

    // Allow Inputs & Outputs.
    connection.setDoInput(true);
    connection.setDoOutput(true);
    connection.setUseCaches(false);

    // Set HTTP method to POST.
    connection.setRequestMethod("POST");

    connection.setRequestProperty("Connection", "Keep-Alive");
    connection.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);

    outputStream = new DataOutputStream( connection.getOutputStream() );
    outputStream.writeBytes(twoHyphens + boundary + lineEnd);
    outputStream.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + pathToOurFile +"\"" + lineEnd);
    outputStream.writeBytes(lineEnd);

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

    // Read file
    bytesRead = fileInputStream.read(buffer, 0, bufferSize);

    while (bytesRead > 0)
    {
        outputStream.write(buffer, 0, bufferSize);
        bytesAvailable = fileInputStream.available();
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        bytesRead = fileInputStream.read(buffer, 0, bufferSize);
    }

    outputStream.writeBytes(lineEnd);
    outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

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

    fileInputStream.close();
    outputStream.flush();
    outputStream.close();
}
catch (Exception ex)
{
    //Exception handling
}
如果在上载文件时需要使用用户名和密码对用户进行身份验证,下面的代码片段将显示如何添加该文件。您所要做的就是在创建连接时设置授权头

String usernamePassword = yourUsername + “:” + yourPassword;
String encodedUsernamePassword = Base64.encodeToString(usernamePassword.getBytes(), Base64.DEFAULT);
connection.setRequestProperty (“Authorization”, “Basic ” + encodedUsernamePassword);
假设PHP脚本负责在服务器端接收数据。此类PHP脚本的示例可能如下所示:

<?php
$target_path  = "./";
$target_path = $target_path . basename( $_FILES['uploadedfile']['name']);
if(move_uploaded_file($_FILES['uploadedfile']['tmp_name'], $target_path)) 
{
    echo "The file ".  basename( $_FILES['uploadedfile']['name']).
 " has been uploaded";
} 
else
{
    echo "There was an error uploading the file, please try again!";
}
?>;

其中uploadsfolder是上载文件的文件夹。如果您计划上载大于默认2MB文件大小限制的文件。您必须修改php.ini文件中的upload\u max\u filesize值。

会出现什么错误?您在服务器端使用什么技术?您确定问题不存在且不在客户机中吗?谢谢您的回复。所以我在GAE上开发了servicede,GAE说raise NOTMAGERROR();我猜字符串编码是错误的,或者必须使用InputStreamBody。我的目标是使用文件名为“img.jpg”的InputStream你介意分享一下你在InputStream实现中是如何编码的吗?你引用的教程使用了MultipartEntity,现在已经不推荐了。也许你应该编辑你的答案,这样人们就可以知道了。上面提到的链接中的帖子似乎不再可用:(@severianojaramillowintanar带来了删除链接中的文本
chmod 777 uploadsfolder