0

誰でも私のAndroidアプリケーションを介してAndroidからビデオをアップロードするためのサンプル/サンプルコードを持っていて、そのビデオをサーバー側に保存できますか?

前もって感謝します..

4

2 に答える 2

2

別の例を次に示します。非常によく似ていますが、最大の違いは、これが他の投稿変数を使用できるように設計されたデータ クラスであることです。たとえば、さまざまなユーザーおよびグループ用の特定のファイル ストアがあるとします。次に、そのデータをビデオと一緒に送信します。このデータ クラスは、サイトへのすべての投稿に実際に使用できます。したがって、データクラスは

public class MultiPartData {
    final String requestURL = "http://www.yoursite.com/some.php";
    final String charset="UTF-8";
    final String boundary="*******";
    private static final String LINE_FEED = "\r\n";
    private HttpURLConnection httpConn;
    private DataOutputStream outputStream;
    private PrintWriter writer;

    //establishes connection
    public MultiPartData() throws IOException {
        URL url = new URL(requestURL);
        httpConn = (HttpURLConnection) url.openConnection();
        httpConn.setUseCaches(false);
        httpConn.setChunkedStreamingMode(4096);
        httpConn.setDoOutput(true); // indicates POST method
        httpConn.setDoInput(true);
        httpConn.setRequestMethod("POST");
        httpConn.setRequestProperty("ENCTYPE", "multipart/form-data");
        httpConn.setRequestProperty("Content-Type",
                "multipart/form-data; boundary=\"" + boundary + "\"");
        httpConn.setRequestProperty("Connection", "Keep-Alive");
        outputStream = new DataOutputStream(httpConn.getOutputStream());
        writer = new PrintWriter(new OutputStreamWriter(outputStream, charset),true);

   }

    //adds post variables to the header body
    public void addFormField(String name, String value) {
        writer.append("--" + boundary).append(LINE_FEED);
        writer.append("Content-Disposition: form-data; name=\"").append(name).append("\"")
            .append(LINE_FEED);
        writer.append("Content-Type: text/plain; charset=" + charset).append(
            LINE_FEED);
        writer.append(LINE_FEED);
        writer.append(value).append(LINE_FEED);
        writer.flush();
    }

    //adds files to header body can be anytype of files
    public void addFilePart(String fieldName, String filePath) throws IOException {
        File uploadFile=new File(filePath);

        String fileName = uploadFile.getName();
        writer.append("--" + boundary).append(LINE_FEED);
        writer.append("Content-Disposition:form-data; name=\"")
                .append(fieldName).append("\"; filename=\"")
                .append(fileName).append("\"")
                .append(LINE_FEED);
        writer.append("Content-Type: ").append(URLConnection.guessContentTypeFromName(fileName))
                .append(LINE_FEED);
        writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
        writer.append(LINE_FEED);
        writer.flush();

        FileInputStream inputStream = new FileInputStream(uploadFile);
        int maxBufferSize=2*1024*1024;
        int bufferSize;
        int bytesAvailable=inputStream.available();
        bufferSize = Math.min(bytesAvailable, maxBufferSize);
        byte[] buffer = new byte[bufferSize];
        int bytesRead=inputStream.read(buffer);
        do {
            outputStream.write(buffer, 0, bytesRead);
            bytesAvailable = inputStream.available();
            bufferSize = Math.min(bytesAvailable, maxBufferSize);
            bytesRead = inputStream.read(buffer, 0, bufferSize);
        }while (bytesRead >0);
        outputStream.flush();
        inputStream.close();

        writer.append(LINE_FEED);
        writer.flush();
    }

    //adds header values to body
    public void addHeaderField(String name, String value) {
        writer.append(name).append(": ").append(value).append(LINE_FEED);
        writer.flush();
    }

    //closing options you must use one of the options to close the  connection
    // finishString()  gets results as a string
    // finnishJOBJECT() gets results as an JSONObject
    // finnishJARRAY() gets results as an JSONArray
    // finnishNoResponse()  closes connection with out looking for response
    public String finishString() throws IOException {
        String response = "";

        writer.append(LINE_FEED).flush();
        writer.append("--" + boundary + "--").append(LINE_FEED);
        writer.close();

        String line;
        StringBuilder sb= new StringBuilder();
        BufferedReader br = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "UTF-8"));
        while ((line=br.readLine()) != null) {
            sb.append(line);
            response =sb.toString();
        }
        br.close();

        return response;
     }
    public JSONObject finnishJOBJECT() throws IOException, JSONException {
        JSONObject response = null;
        writer.append(LINE_FEED).flush();
        writer.append("--" + boundary + "--").append(LINE_FEED);
        writer.close();

        String line;
        StringBuilder sb= new StringBuilder();
        BufferedReader br = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "UTF-8"));
        while ((line=br.readLine()) != null) {
            sb.append(line);
            response =new JSONObject(sb.toString());
        }
        br.close();
        return response;
    }

    public JSONArray finnishJARRAY()throws IOException, JSONException {
        JSONArray response = null;
        writer.append(LINE_FEED).flush();
        writer.append("--" + boundary + "--").append(LINE_FEED);
        writer.close();

        String line;
        StringBuilder sb= new StringBuilder();
        BufferedReader br = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "UTF-8"));
        while ((line=br.readLine()) != null) {
            sb.append(line);
            response =new JSONArray(sb.toString());
        }
        br.close();
        return response;
    }
    public void finnishNoResponse(){
        writer.append(LINE_FEED).flush();
        writer.append("--" + boundary + "--").append(LINE_FEED);
        writer.close();
    }
}

データ クラスを実装する AsyncTask の例は次のようになります。

 public void storeVideoBackground(String filePath,String identifier,String vType,String vName, storeImage serverPath){
    progress.show();
    new storeVideoAsyncTask(filePath,identifier,vType,vName,serverPath).execute();
}
public class storeVideoAsyncTask extends AsyncTask<Void,Void,String>{
    String filePath; //path of the file to be uploaded
    String vType;    //variable used on server
    String vName;    //variable used on server
    String identifier;  //variable used on server
    storeImage serverPath; //interface used to get my response
    MultiPartData upload;  //declares the data class for posting

    public storeVideoAsyncTask(String filePath,String identifier,String vType,String vName, storeImage serverPath){
        this.filePath=filePath;
        this.vName=vName;
        this.vType=vType;
        this.identifier=identifier;
        this.serverPath=serverPath;
    }

    @Override
    protected String doInBackground(Void... params) {
        JSONObject result;
        String sPath="";
        try {
            upload=new MultiPartData();
            upload.addHeaderField("User-Agent", "Android-User");
            upload.addHeaderField("Test-Header","Header-Value");
            upload.addFormField("appAuth",auth); //an auth string compared on server
            upload.addFormField("action","storeVideo");//added post variable
            upload.addFormField("vName",vName);//added post variable
            upload.addFormField("identifier",identifier);//added post variable
            upload.addFormField("vType",vType);//added post variable
            upload.addFilePart("video",filePath);//added file video is the reference on server side to retrieve the file 
            sPath=upload.finishString();//returned server path to be used later
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sPath;
    }

    @Override
    protected void onPostExecute(String servPath) {
        super.onPostExecute(servPath);
        progress.dismiss();
        serverPath.done(servPath);
    }
} 

今は自分のコードを再利用するのが好きなので、これは ServerRequest という別のクラスの一部です。進行状況ダイアログ用にコンテキストを渡し、appAuth などの他の値を宣言します。

このようにファイルが取得されます。これは、任意のスクリプトを使用して投稿変数とやり取りできるサーバー側の PHP です。

 if(isset($_FILES['video']['error'])){
            $path = //path to store video
            $file_name = $_FILES['video']['name'];
            $file_size = $_FILES['video']['size'];
            $file_type = $_FILES['video']['type'];
            $temp_name = $_FILES['video']['tmp_name'];
            if(move_uploaded_file($temp_name, $path.'/'.$file_name)){
                $response =$path.'/'.$file_name;
            }
 }

ポスト変数は通常の方法で取得されます $data=$_POST['data']; このコードがファイルに対して機能しない場合は、サーバー上の何かが原因です。おそらくファイルサイズ。ほとんどのホストされたサーバーでは、投稿サイズ、アップロード ファイル サイズなどに制限があります。一部のサーバーでは、.htaccess でそれをオーバーライドできます。問題をデバッグするには、サーバー側で if(isset in の下にエコーを追加して、エラー コードをエコーアウトします。php のマニュアルには、エラー コードの意味が詳しく説明されています。1 と表示された場合は、.htaccess の php.ini を何かで上書きしてみてください。中はこんな感じ

 php_value post_max_size 30M
 php_value upload_max_filesize 30M
于 2016-02-12T18:01:18.037 に答える
0
public static int uploadtoServer(String sourceFileUri) {
String upLoadServerUri = "your remote server link";
// String [] string = sourceFileUri;
String fileName = sourceFileUri;

HttpURLConnection conn = null;
DataOutputStream dos = null;
DataInputStream inStream = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
String responseFromServer = "";

File sourceFile = new File(sourceFileUri);
if (!sourceFile.isFile()) {
Log.e("My App", "Source File Does not exist");
return 0;
}
try { 
// open a URL connection to the Servlet
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL(upLoadServerUri);
conn = (HttpURLConnection) url.openConnection(); // Open a HTTP  connection to  the URL
conn.setDoInput(true); // Allow Inputs
conn.setDoOutput(true); // Allow Outputs
conn.setUseCaches(false); // Don't use a Cached Copy
conn.setRequestMethod("POST");
conn.setRequestProperty("Connection", "Keep-Alive");
conn.setRequestProperty("ENCTYPE", "multipart/form-data");
conn.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);
conn.setRequestProperty("uploaded_file", fileName);
dos = new DataOutputStream(conn.getOutputStream());

dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"uploaded_file\";filename=\""+ fileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);

bytesAvailable = fileInputStream.available(); // create a buffer of  maximum size
Log.i("My App", "Initial .available : " + bytesAvailable);

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

// read file and write it into form...
bytesRead = fileInputStream.read(buffer, 0, bufferSize);

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

// send multipart form data necesssary after file data...
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);

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

Log.i("Upload file to server", "HTTP Response is : " + serverResponseMessage + ": " + serverResponseCode);
// close streams
Log.i("Upload file to server", fileName + " File is written");
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
ex.printStackTrace();
Log.e("Upload file to server", "error: " + ex.getMessage(), ex);
} catch (Exception e) {
e.printStackTrace();
}
//this block will give the response of upload link
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(conn
 .getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
Log.i("My App", "RES Message: " + line);
}
rd.close();
} catch (IOException ioex) {
Log.e("Huzza", "error: " + ioex.getMessage(), ioex);
}
return serverResponseCode;  // like 200 (Ok)

} // end uploadtoServer
于 2012-09-06T05:04:09.733 に答える