简体   繁体   English

如何在Android上上传图片?

[英]How to upload Image on Android?

I havve to upload image from my SD card to PHP server. 我不得不将图像从SD卡上传到PHP服务器。 I have read a lot of articles and topics but I have some problems... 我读了很多文章和主题,但是有一些问题...

First I have use that code: 首先,我使用该代码:

HttpURLConnection connection = null;
    DataOutputStream outputStream = null;
    //DataInputStream inputStream = null;
    String urlServer = hostName+"Upload";
    String lineEnd = "\r\n";
    String twoHyphens = "--";
    String boundary =  "*****";
    String serverResponseMessage;
    //int serverResponseCode;

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

    try
    {

        showLog("uploading file: " + file);

        FileInputStream fileInputStream = new FileInputStream(new File(pictureFileDir+"/"+file) );

        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=\"uploaded_file\";filename=\"" + file +"\"" + 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();

        showLog("server response: " + serverResponseMessage);

        fileInputStream.close();
        outputStream.flush();
        outputStream.close();
    }
    catch (Exception ex)
    {
        ex.printStackTrace();
    }

but server response 200/OK and no file was on destination server... 但是服务器响应200 / OK,并且目标服务器上没有文件...

After i have read about Multipart: 在我了解Multipart之后:

try {
        HttpParams params = new BasicHttpParams();
        params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
        DefaultHttpClient mHttpClient = new DefaultHttpClient(params); 
        File image = new File(pictureFileDir + "/" + filename);
        HttpPost httppost = new HttpPost(hostName+"Upload");

        MultipartEntity multipartEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);  
        multipartEntity.addPart("Image", new FileBody(image));
        httppost.setEntity(multipartEntity);

        mHttpClient.execute(httppost, new PhotoUploadResponseHandler());

    } catch (Exception e) {
       e.printStackTrace();
    }

but then ai have such LOG in LogCat and nothing else... 但是随后,ai在LogCat中拥有了这样的LOG,除此之外没有其他...

06-04 06:50:52.277: D/dalvikvm(1584): DexOpt: couldn't find static field Lorg/apache/http/message/BasicHeaderValueParser;.INSTANCE 06-04 06:50:52.277: W/dalvikvm(1584): VFY: unable to resolve static field 6688 (INSTANCE) in Lorg/apache/http/message/BasicHeaderValueParser; 06-04 06:50:52.277:D / dalvikvm(1584):DexOpt:找不到静态字段Lorg / apache / http / message / BasicHeaderValueParser; .INSTANCE 06-04 06:50:52.277:W / dalvikvm(1584) ):VFY:无法解析Lorg / apache / http / message / BasicHeaderValueParser中的静态字段6688(INSTANCE); 06-04 06:50:52.277: D/dalvikvm(1584): VFY: replacing opcode 0x62 at 0x001b 06-04 06:50:52.277:D / dalvikvm(1584):VFY:在0x001b处替换操作码0x62

ServerSide Script: ServerSide脚本:

$target_path  = "uploads";
$target_path = $target_path . basename( $_FILES['Image']);
if(move_uploaded_file($_FILES['tmp_name'], $file_path)) {
    echo "success";
} else{
    echo "fail";
}

why? 为什么? What is the simplest way to upload image? 上传图片最简单的方法是什么?

You'll need the httpmime and httpcore libraries for this code. 您需要此代码的httpmimehttpcore库。

Then, do this: 然后,执行以下操作:

try {
    MultipartEntityBuilder mBuilder = MultipartEntityBuilder.create();
    mBuilder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);

    File file = new File(YOUR_ABSOLUTE_PATH_STRING);

    if (!file.exists())
        return null;

    mBuilder.addPart("mFile", new FileBody(file));
}

DefaultHttpClient httpClient = new DefaultHttpClient();

HttpPost httpPost = new HttpPost(YOUR_SERVER_URL);
httpPost.setEntity(mBuilder.build());

HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();

//Reading the response:
InputStream is = httpEntity.getContent();

BufferedReader reader = new BufferedReader(
    new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;

while ((line = reader.readLine()) != null)
    sb.append(line + "\n");

is.close();
httpEntity.consumeContent();
//Do something with the string returned: sb.toString()

} catch (Exception e) {}

PHP Code PHP代码

$fileName = uniqid() . ".png";
if (move_uploaded_file($_FILES["mFile"]["tmp_name"], "uploads/" . $fileName))
    return $fileName;
return "";

This code works for me, so if it doesn't work for you - check the image path you're sending, try a different image etc. 该代码对我有用,因此,如果对您不起作用,请检查您要发送的图像路径,尝试使用其他图像等。

Try this,it is also using multipart, it worked for me. 试试这个,它也使用了multipart,它为我工作。

try {
    String url = "<destination-path>";
    String fileName = ""; //file to be uploaded
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost(url);
    FileBody fileContent = new FiSystem.out.println("hello");
    StringBody comment = new StringBody("Filename: " + fileName);
    MultipartEntity reqEntity = new MultipartEntity();
    reqEntity.addPart("file", fileContent);
    httppost.setEntity(reqEntity);
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity resEntity = response.getEntity();
}

OK finally everything work :) I have used that code: 好了,最后一切正常:)我已经使用了该代码:

try {
    showLog("uploading file: " + file);
    File image = new File(pictureFileDir + "/" + file);

    FileInputStream fileInputStream = new FileInputStream(image);

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

    // Allow Inputs &amp; 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=\"" + pictureFileDir + "/" + file + "\"" + 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();

    showLog("server response: " + serverResponseMessage);

    image.delete();

    fileInputStream.close();
    outputStream.flush();
    outputStream.close();
} catch (Exception ex) {
    ex.printStackTrace();
}

and PHP script: 和PHP脚本:

$target_path  = "uploads/";
$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!";
}

Thanks everyone :) 感谢大家 :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM