0
A
回答
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
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;
}
}
post變量將被檢索通常的方法$ data = $ _ POST ['data']; 如果此代碼不適用於文件,那麼它將會是您服務器上的某些內容的結果。可能是文件大小。大多數託管服務器對郵件大小上傳文件大小等都有限制。有些會讓你在.htaccess中覆蓋它。爲了調試這個問題,在if(在服務器端設置回顯錯誤代碼,並且php手冊有很好的解釋它們的意思的地方加了一個echo),如果它讀取了1,那麼嘗試在.htaccess中用一些東西覆蓋php.ini像這裏面
php_value post_max_size 30M
php_value upload_max_filesize 30M
相關問題
- 1. Android Studio上傳視頻到服務器
- 2. Android視頻上傳到Php服務器?
- 3. 如何將視頻從iOS設備上傳到Django服務器
- 4. 從服務器上傳視頻到Facebook
- 5. 在Android設備上播放視頻的服務器
- 6. 在服務器上傳視頻
- 7. 視頻錄製並將視頻保存在服務器上
- 8. 從android設備上的Facebook牆上上傳視頻?
- 9. 如何在服務器上播放設備上的視頻?
- 10. 加密從Android設備發送到服務器的視頻
- 11. 錄製視頻和音頻並上傳到服務器
- 12. Vimeo的視頻上傳視頻上傳到視頻居然被上傳服務器
- 13. 視頻服務器上
- 14. 上傳視頻文件到服務器
- 15. Swift上傳視頻到Http服務器?
- 16. 在android上使用volley將視頻上傳到服務器
- 17. 如何使用Android錄製視頻並上傳到服務器?
- 18. 視頻js不在android設備上播放視頻
- 19. HTML5視頻元素不能在Android設備上播放視頻?
- 20. 在Android設備上播放視頻
- 21. 在Android設備上的視頻作品
- 22. 在Android設備上播放視頻
- 23. 在Instagram上發佈視頻
- 24. 從Android設備傳輸實時視頻
- 25. 從android應用上傳視頻到http服務器
- 26. 上傳大視頻從Android PHP服務器崩潰應用
- 27. 在Android中上傳視頻
- 28. 在swift上在服務器上上傳視頻
- 29. 檢查視頻上傳到YouTube的進度 - 未發佈視頻
- 30. 上傳從BlackBerry設備的視頻文件到遠程服務器
應該是什麼服務器端代碼? – user861973
不工作的視頻,圖像可以uplod。 – user861973