0

任何人都可以有示例/示例代码,用于通过我的 android 应用程序从 android 上传视频并将该视频存储在服务器端。

提前致谢..

4

2 回答 2

2

这是另一个例子。非常相似,但最大的区别是这是一个数据类,旨在允许其他 post 变量也使用它。例如,您有一个针对不同用户和组的特定文件存储。然后,您希望将该数据与视频一起发送。这个数据类实际上可以用于您网站的所有帖子。所以数据类是

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,您可以使用任何您喜欢的脚本与 post 变量进行交互。

 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 回答