我是学生,只学习Android开发几天, 有一个问题是如何在没有用户界面的情况下在后台上传图像。
我的意思是已经有了文件路径,我不需要用户点击选择图片,当用户运行活动时,图片会自动上传。我知道我可以使用okhttp3,例如下面的视频:
https://www.youtube.com/watch?v=K48jnbM8yS4 (我认为这是好视频,是我的傻瓜,不知道如何修改代码)
但是,在视频中,MainActivity如此
package app.file_upload;
import android.Manifest;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.webkit.MimeTypeMap;
import android.widget.Button;
import com.nbsp.materialfilepicker.MaterialFilePicker;
import com.nbsp.materialfilepicker.ui.FilePickerActivity;
import java.io.File;
import java.io.IOException;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
public class UploadActivity extends AppCompatActivity {
private Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
if(ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED){
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},100);
return;
}
}
enable_button();
}
private void enable_button() {
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
new MaterialFilePicker()
.withActivity(UploadActivity.this)
.withRequestCode(10)
.start();
}
});
}
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
if(requestCode == 100 && (grantResults[0] == PackageManager.PERMISSION_GRANTED)){
enable_button();
}else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},100);
}
}
}
ProgressDialog progress;
@Override
protected void onActivityResult(int requestCode, int resultCode, final Intent data) {
if(requestCode == 10 && resultCode == RESULT_OK){
progress = new ProgressDialog(UploadActivity.this);
progress.setTitle("Uploading");
progress.setMessage("Please wait...");
progress.show();
Thread t = new Thread(new Runnable() {
@Override
public void run() {
File f = new File(data.getStringExtra(FilePickerActivity.RESULT_FILE_PATH));
String content_type = getMimeType(f.getPath());
String file_path = f.getAbsolutePath();
OkHttpClient client = new OkHttpClient();
RequestBody file_body = RequestBody.create(MediaType.parse(content_type),f);
RequestBody request_body = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("type",content_type)
.addFormDataPart("uploaded_file",file_path.substring(file_path.lastIndexOf("/")+1), file_body)
.build();
Request request = new Request.Builder()
.url("URL_TO_THE_SERVER/YOUR_SCRIPT.php")
.post(request_body)
.build();
try {
Response response = client.newCall(request).execute();
if(!response.isSuccessful()){
throw new IOException("Error : "+response);
}
progress.dismiss();
} catch (IOException e) {
e.printStackTrace();
}
}
});
t.start();
}
}
private String getMimeType(String path) {
String extension = MimeTypeMap.getFileExtensionFromUrl(path);
return MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
}
}
对于我的情况,我只上传图片,但是我不需要用户界面(比如选择图片的按钮),所以我试着修改代码,如下图所示:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
File f = new File(" /storage/emulated/0/Android/data/abc.package.name/files/images.jpg");
String content_type = getMimeType(f.getPath());
String file_path = f.getAbsolutePath();
OkHttpClient client = new OkHttpClient();
RequestBody file_body = RequestBody.create(MediaType.parse(content_type),f);
RequestBody request_body = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("type",content_type)
.addFormDataPart("uploaded_file",file_path.substring(file_path.lastIndexOf("/")+1), file_body)
.build();
Request request = new Request.Builder()
.url("My php File Link ")
.post(request_body)
.build();
try {
Response response = client.newCall(request).execute();
if(!response.isSuccessful()){
throw new IOException("Error : "+response);
}
} catch (IOException e) {
e.printStackTrace();
}
}
private String getMimeType(String path) {
String extension = MimeTypeMap.getFileExtensionFromUrl(path);
return MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
}
}
我只需要使用okhttp3在后台任务上传图像,不需要任何界面,但我觉得我很难,也许我是android studio的新用户...> _<
任何人都可以帮我修改代码....
我的PHP代码也在这里:
<?php
$file_path = "images/";
$file_path = $file_path . basename($_FILES['uploaded_file']['name']);
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'],$file_path)) {
echo "success";
}else {
echo "error";
}
?>