1

我有 Rest Api 的链接和用 C sharp 上传图像的示例代码,但是如何使用 java 将图像从 android 上传到服务器同样的事情

这是示例代码

http://xx.xx.xxx.xx/restservice/photos

Sample code for uploading file:
 string requestUrl = string.Format("{0}/UploadPhoto/{1}", url,filnm);
//file name should be uniqque
                HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(requestUrl);
                request.Method = "POST";
                request.ContentType = "text/plain";
                byte[] fileToSend = FileUpload1.FileBytes; //File bytes
                request.ContentLength = fileToSend.Length;

                using (Stream requestStream = request.GetRequestStream())
                {
                    // Send the file as body request.
                    requestStream.Write(fileToSend, 0, fileToSend.Length);
                    requestStream.Close();
                }

                using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                    Console.WriteLine("HTTP/{0} {1} {2}", response.ProtocolVersion, (int)response.StatusCode, response.StatusDescription);

你将如何使用 android

编辑:

在您的回答的帮助下,我在这里编写了代码,但我收到了 404 连接响应和 ERROR ERROR

    public class ImageUploadToServer extends Activity {

    TextView messageText;
    Button uploadButton;

    String upLoadServerUri = null;
    String urlLink = "http://xx.xx.xxx.xx/restservice/photos/";
    String path= Environment.getExternalStorageDirectory().getAbsolutePath()+"/myimg.jpg";

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_upload_to_server);

        uploadButton = (Button)findViewById(R.id.uploadButton);
        messageText  = (TextView)findViewById(R.id.messageText);
        uploadData();

    }

    public void uploadData ()
    {

        HttpURLConnection connection = null;
        DataOutputStream outputStream = null;  
        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(path));

             File sourceFile = new File(path); 

             FileInputStream fileInputStream = new FileInputStream(sourceFile);

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

             Log.d("Connection:", "Connection" + connection.getResponseCode());

             connection.setDoInput(true);
             connection.setDoOutput(true);
             connection.setUseCaches(false);

             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=\""
                             + path + "\"" + lineEnd);
             outputStream.writeBytes(lineEnd);

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

             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);

             fileInputStream.close();
             outputStream.flush();
             outputStream.close();

             InputStream responseStream = new BufferedInputStream(connection.getInputStream());

             BufferedReader responseStreamReader = new BufferedReader(new InputStreamReader(responseStream));
             String line = "";
             StringBuilder stringBuilder = new StringBuilder();
             while ((line = responseStreamReader.readLine()) != null) {
                 stringBuilder.append(line).append("\n");
             }
             responseStreamReader.close();

             String response = stringBuilder.toString();
             Log.w("SERVER RESPONE: ", "Server Respone" + response);

             responseStream.close();
             connection.disconnect();

         } catch (Exception ex) {
             Log.i("UPLOAD ERROR", "ERROR ERROR");
         }

    }


}
4

3 回答 3

1

我目前正在使用此代码将小视频上传到服务器(PHP 服务器端)。

不要认为不再支持 apache HttpClient,所以 HttpURLConnection 是要走的路。

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

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

        connection.setDoInput(true);
        connection.setDoOutput(true);
        connection.setUseCaches(false);

        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=\""
                        + path + "\"" + lineEnd);
        outputStream.writeBytes(lineEnd);

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

        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);

        fileInputStream.close();
        outputStream.flush();
        outputStream.close();

        InputStream responseStream = new BufferedInputStream(connection.getInputStream());

        BufferedReader responseStreamReader = new BufferedReader(new InputStreamReader(responseStream));
        String line = "";
        StringBuilder stringBuilder = new StringBuilder();
        while ((line = responseStreamReader.readLine()) != null) {
            stringBuilder.append(line).append("\n");
        }
        responseStreamReader.close();

        String response = stringBuilder.toString();
        Log.w("SERVER RESPONE: ", response);

        responseStream.close();
        connection.disconnect();

    } catch (Exception ex) {
        Log.i("UPLOAD ERROR", "ERROR ERROR");
    }
}
于 2014-02-22T13:08:41.703 回答
0

这是可以帮助您在服务器上接收文件的 PHP。

<?php

try {


    // Checking for upload attack and rendering invalid.
    if (
        !isset($_FILES['uploadedfile']['error']) ||
        is_array($_FILES['uploadedfile']['error'])
    ) {
        throw new RuntimeException('Invalid parameters.');
    }

    // checking for error value on upload
    switch ($_FILES['uploadedfile']['error']) {
        case UPLOAD_ERR_OK:
            break;
        case UPLOAD_ERR_NO_FILE:
            throw new RuntimeException('No file sent.');
        case UPLOAD_ERR_INI_SIZE:
        case UPLOAD_ERR_FORM_SIZE:
            throw new RuntimeException('Exceeded filesize limit.');
        default:
            throw new RuntimeException('Unknown errors.');
    }

    // checking file size 
    if ($_FILES['uploadedfile']['size'] > 1000000) {
        throw new RuntimeException('Exceeded filesize limit.');
    }


    // checking MIME type for mp4... change this to suit your needs
    $finfo = new finfo(FILEINFO_MIME_TYPE);
    if (false === $ext = array_search(
        $finfo->file($_FILES['uploadedfile']['tmp_name']),
        array(
            'mp4' => 'video/mp4',
        ),
        true
    )) {
        throw new RuntimeException('Invalid file format.');
    }


    // Uniquely naming each uploaded for file
    if (!move_uploaded_file(
        $_FILES['uploadedfile']['tmp_name'],
        sprintf('./uploads/%s.%s',
            sha1_file($_FILES['uploadedfile']['tmp_name']),
            $ext
        )
    )) {
        throw new RuntimeException('Failed to move uploaded file.');
    }
    // response code.
    echo 'File is uploaded successfully!';

}
catch (RuntimeException $e) {

    echo $e->getMessage();

}

?>
于 2014-02-23T23:19:31.717 回答
0

尝试这个....

public static JSONObject postFile(String url,String filePath,int id){

String result="";
HttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);

File file = new File(filePath);
MultipartEntity mpEntity = new MultipartEntity();
ContentBody cbFile = new FileBody(file, "image/jpeg");

StringBody stringBody= null;
JSONObject responseObject=null;

try {
    stringBody = new StringBody(id+"");
    mpEntity.addPart("file", cbFile);
    mpEntity.addPart("id",stringBody);
    httpPost.setEntity(mpEntity);
    System.out.println("executing request " + httpPost.getRequestLine());
    HttpResponse response = httpClient.execute(httpPost);
    HttpEntity resEntity = response.getEntity();
    result=resEntity.toString();
    responseObject=new JSONObject(result);
} 
catch (UnsupportedEncodingException e) {
    e.printStackTrace();
} 
catch (ClientProtocolException e) {
    e.printStackTrace();
} 
catch (IOException e) {
    e.printStackTrace();
} 
catch (JSONException e) {
    e.printStackTrace();
}
return responseObject;
}
于 2016-08-22T11:07:13.767 回答