繁体   English   中英

使用 HttpPost 上传文件 Android

[英]Using HttpPost to upload file Android

我上传这个文件对吗? 这是我的代码:


删除的代码

它基本上只是一个将文件 (csv) 发送到 Web 服务器的异步任务。

我正在返回状态代码 400:( 谁知道我做错了什么?


编辑:现在我返回状态代码 411,但是当我指定内容长度时,它返回 ClientProtocolException。

现在是我的代码:

UploadTask uploadtask;

    public class UploadTask extends AsyncTask<Void, byte[], Boolean> {

        HttpPost httppost;

        @Override
        protected Boolean doInBackground(Void... params) {
            Boolean result = false;
            String id = projectIDs.get((int) spinner.getSelectedItemId());

            Log.i("TAG", id);
            try {

                l(send(String.valueOf(id), "http://" + site
                        + "/restlet/position.csv?project=" + id,
                        "/csv.csv"));

            } catch (ClientProtocolException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }

            return result;
        }

        private void entity(String id, String file) throws JSONException,
                UnsupportedEncodingException, FileNotFoundException {
            // Add your data
            File myFile = new File(Environment.getExternalStorageDirectory(),
                    file);

            FileEntity fileEntity = new FileEntity(myFile, "multipart/form-data;");
            fileEntity.setChunked(true);
            long len = fileEntity.getContentLength();
            httppost.getParams().setParameter("project", id);
            httppost.setEntity(fileEntity);

            //httppost.addHeader("Content-Length",String.valueOf(len));
            httppost.setHeader("Content-Length", String.valueOf(len));
        }

        private String send(String id, String URL, String file)
                throws ClientProtocolException, IOException, JSONException {

            l(URL);

            HttpResponse response = null;

            httppost = new HttpPost(URL);

            entity(id, file);

            response = httpclient.execute(httppost);

            Header[] head = response.getAllHeaders();

            String str = String.valueOf(response.getStatusLine()
                    .getStatusCode());

            response.getEntity().consumeContent();

            return str;
        }

    }

此处的代码用于将文件上传到 Web 服务器:) 经过数小时的努力,我得到了它,但是不得不从 apache 导入 MultipartEntity、StringBody 和 FileBody

httppost = new HttpPost(URL);
MultipartEntity entity = new MultipartEntity();
entity.addPart("title", new StringBody("position.csv", Charset.forName("UTF-8")));
File myFile = new File(Environment.getExternalStorageDirectory(), file);
FileBody fileBody = new FileBody(myFile);
entity.addPart("file", fileBody);
httppost.setEntity(entity);
httppost.getParams().setParameter("project", id);

在任何事情之前

1-选择文件使用这个或无论如何选择它

https://github.com/iPaulPro/aFileChooser只需导入它

2-不要忘记将其添加到清单中

   <\uses-permission android:name="android.permission.INTERNET" />
  <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
  <uses-permission android:name="android.permission.RECORD_AUDIO" />

3- 不要忘记更改 java 代码中的 uri 和 php 代码中的文件夹名称

4- 只需复制并粘贴此代码即可,我试过了并且 100% 有效

爪哇

package com.example.uploadthestupidfile;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import com.ipaulpro.afilechooser.utils.FileUtils;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

@SuppressLint("NewApi")
public class MainActivity extends Activity
  {
private static final int FILE_SELECT_CODE = 0;
@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    StrictMode.ThreadPolicy policy=new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);
      Intent intent = new Intent(Intent.ACTION_GET_CONTENT); 
        intent.setType("*/*"); 
        intent.addCategory(Intent.CATEGORY_OPENABLE);

        try {
            startActivityForResult(
                    Intent.createChooser(intent, "Select a File to Upload"),
                    FILE_SELECT_CODE);
        } catch (android.content.ActivityNotFoundException ex) {
            // Potentially direct the user to the Market with a Dialog
            Toast.makeText(this, "Please install a File Manager.", 
                    Toast.LENGTH_SHORT).show();
        }

}

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data)    {
    switch (requestCode) {
        case FILE_SELECT_CODE:
        if (resultCode == RESULT_OK) {
            // Get the Uri of the selected file 
            Uri uri = data.getData();
          //  Log.d(TAG, "File Uri: " + uri.toString());
            // Get the path
            String path = FileUtils.getPath(this, uri);

            Toast.makeText(this,""+path,Toast.LENGTH_LONG).show();

            try {
                upload(path);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                Toast.makeText(this,"ErrorS",Toast.LENGTH_LONG).show();
            }
        //    Log.d(TAG, "File Path: " + path);
            // Get the file instance
            // File file = new File(path);
            // Initiate the upload
        }
        break;
    }
    super.onActivityResult(requestCode, resultCode, data);
}
 public void upload(String selectedPath) throws Exception {

        HttpURLConnection connection = null;
        DataOutputStream outputStream = null;
        DataInputStream inputStream = null;

        String pathToOurFile = selectedPath;
        String urlServer = "http://yoursite/upload_files.php";
        String lineEnd = "\r\n";
        String twoHyphens = "--";
        String boundary = "*****";

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

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

            URL url = new URL(urlServer);
            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=\""
                            + pathToOurFile + "\"" + 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);

            int serverResponseCode = connection.getResponseCode();
            String serverResponseMessage = connection.getResponseMessage();

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

    }

}

PHP 上传文件.php

 <?php
$target_path = "uploadedimages/"; //here folder name 
$target_path = $target_path . basename($_FILES['uploadedfile']['name']);

error_log("Upload File >>" . $target_path . $_FILES['error'] . " \r\n", 3,
"Log.log");

error_log("Upload File >>" . basename($_FILES['uploadedfile']['name']) . "     \r\n",
3, "Log.log");

 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!";
  }
 ?>

暂无
暂无

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

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