Я новичок в Android. Недавно я разрабатываю приложение, которое загружает изображение с текстом с помощью Android Studio.
У меня возникли некоторые проблемы при разработке приложения. Я могу загрузить изображение на сервер. Однако я столкнулся с проблемой загрузки текста с изображением. Я действительно не знаю, где идет не так. Я надеюсь, что я могу получить некоторые рекомендации здесь, и вы можете изменить код.
MainActivity.java
private void uploadVideo(final String name) {
class UploadVideo extends AsyncTask<Void, Void, String> {
ProgressDialog uploading;
@Override
protected void onPreExecute() {
super.onPreExecute();
uploading = ProgressDialog.show(MainActivityUpload.this, "Uploading File", "Please wait...", false, false);
}
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
uploading.dismiss();
textViewResponse.setText(Html.fromHtml("<b>Uploaded at <a href='" + s + "'>" + s + "</a></b>"));
textViewResponse.setMovementMethod(LinkMovementMethod.getInstance());
}
@Override
protected String doInBackground(Void... params) {
upload u = new upload();
String msg = u.uploadVideo(selectedPath , name); //the name is passed uploadVideo function in upload.java
return msg;
}
}
UploadVideo uv = new UploadVideo();
uv.execute();
}
upload.java
public class upload {
public static final String UPLOAD_URL= "http://192.168.1.10/VideoUpload/upload.php";
private int serverResponseCode;
public String uploadVideo(String file , String name) {
String fileName = file;
HttpURLConnection conn = null;
DataOutputStream dos = null;
String lineEnd = "\r\n";
String twoHyphens = "--";
String boundary = "*****";
int bytesRead, bytesAvailable, bufferSize;
byte[] buffer;
int maxBufferSize = 1 * 1024 * 1024;
File sourceFile = new File(file);
if (!sourceFile.isFile()) {
Log.e("Huzza", "Source File Does not exist");
return null;
}
try {
FileInputStream fileInputStream = new FileInputStream(sourceFile);
URL url = new URL(UPLOAD_URL);
conn = (HttpURLConnection) url.openConnection();
conn.setDoInput(true);
conn.setDoOutput(true);
conn.setUseCaches(false);
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("myFile", fileName);
conn.setRequestProperty("name", name); //the name of the image is passed here
dos = new DataOutputStream(conn.getOutputStream());
dos.writeBytes(twoHyphens + boundary + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"myFile\";filename=\"" + fileName + "\"" + lineEnd);
dos.writeBytes(lineEnd);
bytesAvailable = fileInputStream.available();
Log.i("Huzza", "Initial .available : " + bytesAvailable);
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
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);
}
dos.writeBytes(lineEnd);
dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
dos.writeBytes("Content-Disposition: form-data; name=\"name\"" + lineEnd);
dos.writeBytes(lineEnd);
dos.writeBytes(name + lineEnd);
dos.writeBytes(twoHyphens + boundary + lineEnd);
serverResponseCode = conn.getResponseCode();
fileInputStream.close();
dos.flush();
dos.close();
} catch (MalformedURLException ex) {
ex.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
if (serverResponseCode == 200) {
StringBuilder sb = new StringBuilder();
try {
BufferedReader rd = new BufferedReader(new InputStreamReader(conn
.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
sb.append(line);
}
rd.close();
} catch (IOException ioex) {
}
return sb.toString();
}else {
return "Could not upload";
}
}
}
upload.php
<?php
if($_SERVER['REQUEST_METHOD']=='POST'){
$file_name = $_FILES['myFile']['name'];
$file_size = $_FILES['myFile']['size'];
$file_type = $_FILES['myFile']['type'];
$temp_name = $_FILES['myFile']['tmp_name'];
$name = $_POST['name'];
require_once('dbConnect.php');
$sql ="SELECT id FROM uploads ORDER BY id ASC";
$res = mysqli_query($con,$sql);
$id = 0;
while($row = mysqli_fetch_array($res)){
$id = $row['id'];
}
$location = "uploads/";
$actualpath = "http://192.168.1.9/VideoUpload/$location$file_name";
$sql = "INSERT INTO uploads (image,name) VALUES ('$actualpath','$name')";
if(mysqli_query($con,$sql)){
move_uploaded_file($temp_name, $location.$file_name);
echo "Successfully Uploaded";
}
mysqli_close($con);
}else{
echo "Error";
}
?>
Задача ещё не решена.
Других решений пока нет …