无法将SD卡上的图像上传到php服务器

时间:2018-04-18 02:24:02

标签: android file image-uploading

我一直在尝试使用Android上传服务将图片上传到php服务器。但只有当文件在手机内存中时,上传才有效。如果文件在外部SD卡上,没有运气。

      try {
        String uploadId = UUID.randomUUID().toString();
        new MultipartUploadRequest(this, uploadId, Constant.URL + "/lecture/save?token=" + token)
                .addFileToUpload(f.getAbsolutePath(), "notes_image")
                .addParameter("class_code", classId)
                .addParameter("section_code", sectionNameId)
                .addParameter("subject_code", subjectNameId)
                .addParameter("lecture_title", lectureTitleEditText.getEditableText().toString())
                .addParameter("notes", lectureNotesEditText.getEditableText().toString())
                .addParameter("pdf", base64EncodedPdfString)
                .addParameter("file_extension", "pdf")
                .setNotificationConfig(new UploadNotificationConfig())
                .setMaxRetries(5)
                .startUpload();
        Toast.makeText(this, "uploaded successfully", Toast.LENGTH_SHORT).show();
    } catch (Exception e) {
        Log.e("error during upload", String.valueOf(e.getLocalizedMessage()));
    }

我认为问题在于我为上传请求提供的文件路径。以下是我为实现这条道路所做的工作。

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == PICK_FILE_CODE && resultCode == RESULT_OK && data != null) {
            fileUriImage = data.getData();
            filePathImage = data.getData().getPath();
    String uriString = fileUriImage.toString();
    File myFile = new File(uriString);
    String asbolutePath = myFile.getAbsolutePath();
    Log.d("ABSOLUTE PATH", asbolutePath);
    if (uriString.startsWith("content://")) {
        Cursor cursor = null;
        try {
            cursor = getApplicationContext().getContentResolver().query(fileUriImage, null, null, null, null);
            if (cursor != null && cursor.moveToFirst()) {
                displayName = cursor.getString(cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME));
            }
        } finally {
            cursor.close();
        }
    } else if (uriString.startsWith("file://")) {
        displayName = myFile.getName();
    }
    File sdCard = Environment.getExternalStorageDirectory();
    File dir = new File(sdCard.getAbsolutePath());
    dir.mkdir();
    File f = new File(dir, displayName);
    if (!f.exists()) {
        try {
            f.createNewFile();

        } catch (IOException e) {
            e.printStackTrace();
            Log.d("error creating file", e.getMessage());
        }
    }
}
}

0 个答案:

没有答案