我是android的新手,我正在尝试使用离子库将文件上传到服务器 ion library但文件崩溃了。有这个错误。
FATAL EXCEPTION: Thread-55725
Process: transitions.com.example.huzy_kamz.interview, PID: 4635
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
at android.os.Handler.<init>(Handler.java:209)
at android.os.Handler.<init>(Handler.java:123)
at android.app.Dialog.<init>(Dialog.java:122)
at android.app.AlertDialog.<init>(AlertDialog.java:200)
at android.app.AlertDialog.<init>(AlertDialog.java:196)
at android.app.AlertDialog.<init>(AlertDialog.java:141)
at android.app.ProgressDialog.<init>(ProgressDialog.java:77)
at transitions.com.example.huzy_kamz.interview.MainActivity.uploadFile(MainActivity.java:131)
at transitions.com.example.huzy_kamz.interview.MainActivity$2$1.run(MainActivity.java:66)
at java.lang.Thread.run(Thread.java:818)
这是使用离子库上传文件的方法
public class MainActivity extends AppCompatActivity {
private static final int PICK_FILE_REQUEST = 1;
private static final String TAG = MainActivity.class.getSimpleName();
private String selectedFilePath;
private String SERVER_URL = "http://192.168.43.104:8093/PoliceApp/FileUpload.aspx";
ImageView ivAttachment;
private String UPLOAD_URL ="http://192.168.43.104:8093/PoliceApp/ImageUpload.aspx";
ProgressDialog dialog;
private ImageView imageView;
private EditText firstname_edt,lastname_edt,email_edt,jobtitle_edt,source_edt;
private TextView directory_txt;
private Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView= (ImageView)findViewById(R.id.imageView);
firstname_edt=(EditText)findViewById(R.id.firstname_edt);
lastname_edt=(EditText)findViewById(R.id.lastname_edt);
email_edt=(EditText)findViewById(R.id.email_edt);
jobtitle_edt=(EditText)findViewById(R.id.jobtitle_edt);
source_edt=(EditText)findViewById(R.id.source_edt);
button=(Button)findViewById(R.id.button);
directory_txt=(TextView)findViewById(R.id.directory_txt);
imageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
showFileChooser();
}
});
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(selectedFilePath != null){
dialog = ProgressDialog.show(MainActivity.this,"","Uploading File...",true);
new Thread(new Runnable() {
@Override
public void run() {
//creating new thread to handle Http Operations
uploadFile(selectedFilePath);
// OnSendFileInfo();
}
}).start();
}else{
Toast.makeText(MainActivity.this,"Please choose a File First",Toast.LENGTH_SHORT).show();
}
}
});
}
// Gallery pick
private void showFileChooser() {
Intent intent = new Intent();
//sets the select file to all types of files
intent.setType("*/*");
//allows to select data and return it
intent.setAction(Intent.ACTION_GET_CONTENT);
//starts new activity to select file and return data
startActivityForResult(Intent.createChooser(intent,"Choose File to Upload.."),PICK_FILE_REQUEST);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == Activity.RESULT_OK){
if(requestCode == PICK_FILE_REQUEST){
if(data == null){
//no data present
return;
}
Uri selectedFileUri = data.getData();
selectedFilePath = FilePath.getPath(this,selectedFileUri);
Log.i(TAG,"Selected File Path:" + selectedFilePath);
if(selectedFilePath != null && !selectedFilePath.equals("")){
directory_txt.setText(selectedFilePath);
}else{
Toast.makeText(this,"Cannot upload file to server",Toast.LENGTH_SHORT).show();
}
}
}
}
public void uploadFile(final String selectedFilePath){
final ProgressDialog pd;
pd = new ProgressDialog(MainActivity.this);
pd.setMessage("Uploading File...");
pd.setCancelable(false);
pd.show();
final String url_ = "";
Ion.with(MainActivity.this)
.load(SERVER_URL)
.uploadProgressDialog(pd)
.setMultipartParameter("uploaded_file",selectedFilePath)
.setMultipartFile("archive", "application/zip", new File(selectedFilePath))
.asString()
.setCallback(new FutureCallback<String>() {
@Override
public void onCompleted(Exception e, String result) {
Toast.makeText(MainActivity.this," "+result,Toast.LENGTH_LONG).show();
pd.dismiss();
}
});
}
}
我的方法包含上传PDF文件的离子库。
public void uploadFile(final String selectedFilePath){
final ProgressDialog pd;
pd = new ProgressDialog(MainActivity.this);
pd.setMessage("Uploading ...");
pd.setCancelable(false);
pd.show();
final String url_ = "";
//File file = new File(this.getFilesDir().getAbsolutePath() + "/thesubdirectory/the.zip");
File f = new File(getApplicationContext().getFilesDir().getAbsolutePath()+selectedFilePath);
try {
RandomAccessFile rf = new RandomAccessFile(f, "rw");
rf.setLength(1024 * 1024 * 2);
} catch (Exception e) {
System.err.println(e);
}
File echoedFile = getFileStreamPath("echo");
Ion.with(MainActivity.this)
.load(SERVER_URL)
.uploadProgressDialog(pd)
.setMultipartFile("uploaded_file",f)
.write(echoedFile)
.setCallback(new FutureCallback<File>() {
@Override
public void onCompleted(Exception e, File result) {
try {
Toast.makeText(MainActivity.this, " " + result, Toast.LENGTH_LONG).show();
System.out.println("Error " + result);
pd.dismiss();
} catch (Exception e1) {
System.out.println("Error " + e1);
}
pd.dismiss();
}
});
}
我不错,我需要你的帮助,我错了。 我的后端工作正常,但问题出在上传过程中。
这是我在C#Api中找到指定文件夹中的文件。
public void FileSave(HttpPostedFile file)
{
try
{
if (file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/FileStorage"), fileName);
file.SaveAs(path);
}
Response.Write("Upload successfull");
}
catch
{
Response.Write("An Error Ocurred");
}
}
答案 0 :(得分:1)
从Ion调用链中移除线程,因为Ion为您管理,而您的异常与Ion FYI无关。
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(selectedFilePath != null){
dialog = ProgressDialog.show(MainActivity.this,"","Uploading File...",true);
uploadFile(selectedFilePath);
// OnSendFileInfo();
}else{
Toast.makeText(MainActivity.this,"Please choose a File First",Toast.LENGTH_SHORT).show();
}
}
});
您无法在非Ui线程中使用View。因此,当我看到你正在上传方法中创建一个进度对话框时,该对话框正在为一个线程调用。该代码应仅在主线程中。
答案 1 :(得分:0)
我找到了一种上传或发布 multipart / form-data 的简单方法,上传进度条。可能这可能会有所帮助。
假设您的服务器正在等待以下数据:
1. 文件(PDF,图像,音频,视频等)。
2 命名强>
3 电子邮件强>
4. <强>地址。强>
并且您希望在网址中上传一次该信息绝对网址或相对网址,离子库简单,准确,高效且更好这个。
第1步:
声明您的URI
private Uri filePath;
第2步:
然后从您的图库中选择文件,在这里您可以选择识别您希望用户查看的任何类型的文件,我在这里确定了一个PDF文件。
在这一行intent.setType("application/pdf");
private void showFileChooser() {
Intent intent = new Intent();
intent.setType("application/pdf");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Pdf"), PICK_PDF_REQUEST);
}
//handling the image chooser activity result
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_PDF_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
filePath = data.getData();
Toast.makeText(getApplicationContext(), "" + filePath, Toast.LENGTH_LONG).show();
}
}
然后,您可以在showFileChooser()
中致电Button
点按一下即可访问您的图库。
第3步:
a)创建一个包含离子库的方法Upload()
来启动作业。如果您在此方法中看到,我首先声明file,name, email,address
,file
它获取所选文件或路径文件的 URI 数据,然后name, email,address
,它从EditText获取数据,你必须声明EditText来获取数据。
b)然后确定要在Posting
我的url_
POST
中使用的网址。但请确保在加载部分.load("POST",url_)
中加入.setMultipartFile("File", file)
。
c)然后通过设置 MultipartParameter .setMultipartParameter("Name", name)
等来使用public void Upload() {
String file= FilePath.getPath(this, filePath);
final String name = name_edt.getText().toString();
final String email = email_edt.getText().toString();
final String address = address_edt.getText().toString();
final ProgressDialog pd;
pd = new ProgressDialog(MainActivity.this);
pd.setMessage("Logging in...");
pd.setCancelable(false);
pd.show();
final String url_ = "xxxxxxxxxxxxxxx";
final File file = new File(Uri.parse(path).toString());
Ion.with(MainActivity.this)
.load("POST",url_)
.progressDialog(pd)
.setMultipartFile("file", file)
.setMultipartParameter("Name", name)
.setMultipartParameter("Email", email)
.setMultipartParameter("Address.", address)
.asString()
.setCallback(new FutureCallback<String>() {
@Override
public void onCompleted(Exception e, String result) {
// Toast.makeText(getApplicationContext(),""+file,Toast.LENGTH_LONG).show();
System.out.println("Error " + e);
// Toast.makeText(getApplicationContext(), "Exception : " + e, Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), result, Toast.LENGTH_LONG).show();
// Toast.makeText(getApplicationContext(),""+e,Toast.LENGTH_LONG).show();
pd.dismiss();
}
});
}
和其余参数设置文件。
Php
然后你很高兴,根据你的C#API,该文件将能够保存在文件夹中。甚至其他人使用gabsty new
或任何其他语言,您可以创建自己的Api来保存服务器文件夹中的文件
希望它运作良好。