使用ion库在Android中将文件(多部分/表单数据)上传到服务器失败 [英] Uploading a File (Multipart/Form data) to Server Failed in Android using ion library

查看:89
本文介绍了使用ion库在Android中将文件(多部分/表单数据)上传到服务器失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是android的新手,正在尝试使用ion库将文件上传到服务器 离子库,但是文件崩溃.出现此错误.

I am new in android ,and am trying to upload a file to server using ion library ion library but the file crashes. with this error.

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)

这是使用离子库上传我的文件的方式

This is how am using ion library to upload my file

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();


                        }
                    });



    }

我没有错,请帮忙,我错了. 我的后端工作正常,但是问题出在上传过程中.

I don't where am wrong please i need your help, where am i wrong. My back end is working fine , but the problem is in the uploading process.

这是我的C#Api,用于在指定文件夹中找到文件.

This is my C# Api to locate the File in a specified folder.

 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");

        }
    }

推荐答案

我发现了一种使用上传进度条上传或发布 multipart/form-data 的简单方法.可能对您有帮助.

Well i have found out a simple way of uploading or posting multipart/form-data with an upload progress bar. may be this could help.

假设您的服务器正在等待以下数据:

1. 文件(PDF,图像,音频,视频等).

1.File(PDF,Image,Audio,Video etc.).

2. 名称

3. 电子邮件

4. 地址.

,并且您希望一次通过绝对URL 相对URL 上载该信息,因此离子库简单,精确,高效,并且在这个.

and you want to upload that information once in a URL be it an Absolute URL or a Relative URL, ion library is easy , precise, efficient and much better in this.

步骤1:

声明您的URI

private Uri filePath;

步骤2:

然后从图库中选择文件,在这里您可以选择您希望用户查看的任何类型的文件,在这里,我已经确定了PDF文件. 在这行intent.setType("application/pdf");

then Pick the file from your gallery , here it's your choice you identify any kind of files you want a user to view, me here i have identified a PDF file. on this line 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();
        }
    }

然后您可以在Button中调用showFileChooser()进行单击以访问您的画廊.

then you can call showFileChooser() in the Button for a click to access your gallery.

步骤3:

a)创建包含离子库的方法Upload()以开始作业.如果您在此方法中看到,我首先声明file,name, email,address,对于file,它获取所选文件或路径文件的 URI 数据,然后name, email,address,它从以下位置获取数据EditText,您必须声明EditText才能获取数据.

a) Make a method Upload() containing ion library to start the job. If you see in this method , i first declared the file,name, email,address , for file it gets the URI data of a selected file or the path file , then name, email,address, it gets the data from EditText , you have to declare EditText to get the data.

b)然后确定要在Posting中使用的 URL url_.但请确保在 load 部分.load("POST",url_)中包含POST. c)然后使用.setMultipartFile("File", file)设置文件,并通过设置 MultipartParameter .setMultipartParameter("Name", name)等设置其余参数.

b) Then identify the URL you want to use in Posting mine is url_. but make sure you include POST, in the load section .load("POST",url_). c) Then you set the file by using .setMultipartFile("File", file) and the rest of the parameters by setting MultipartParameter .setMultipartParameter("Name", name) and so on.

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();


                    }
                });
    }

然后您就可以使用C#API进行操作了,该文件将可以保存在Folder中.甚至其他人也使用Php或任何其他语言,您可以创建自己的Api来将文件保存在服务器文件夹中

Then you are good to go , according to your C# API , the file will be able to save in the Folder. Even others use Php or any other language you can create your own Api to save a file in your server folder

希望它运作良好.

这篇关于使用ion库在Android中将文件(多部分/表单数据)上传到服务器失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆