android.webkit.MimeTypeMap Java Examples

The following examples show how to use android.webkit.MimeTypeMap. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: MediaUtils.java    From Android-RTEditor with Apache License 2.0 6 votes vote down vote up
public static File createUniqueFile(File targetFolder, String originalFile, String mimeType, boolean keepOriginal) {
    /*
     * We try to get the extension from the file name first.
     * If that fails (e.g. for images provided by the picasa content provider)
     * we use the mime type to determine the extension.
     * The extension is important to be able to determine the correct content type
     * once we create a MIME message.
     */
    String extension = FilenameUtils.getExtension(originalFile);
    if (isNullOrEmpty(extension)) {
        extension = MimeTypeMap.getSingleton().getExtensionFromMimeType(mimeType);
    }

    String random = Long.toString(Math.round(Math.random() * Integer.MAX_VALUE));        // random part
    long timestamp = Calendar.getInstance().getTimeInMillis();                            // time stamp

    if (keepOriginal) {
        String baseName = FilenameUtils.getBaseName(originalFile);
        return new File(targetFolder + File.separator + baseName + "_" + random + "_" + timestamp + "." + extension);
    } else {
        return new File(targetFolder + File.separator + random + "_" + timestamp + "." + extension);
    }
}
 
Example #2
Source File: FileProvider.java    From DeviceConnect-Android with MIT License 6 votes vote down vote up
/**
 * ファイル名からMIMEタイプ取得.
 *
 * @param file ファイル
 * @return MIMEタイプ
 */
private String getMIMEType(final File file) {
    // 拡張子を取得
    String fileName = file.getName();
    int pos = fileName.lastIndexOf(".");
    String ext = (pos >= 0) ? fileName.substring(pos + 1) : null;
    if (ext != null) {
        // 小文字に変換
        ext = ext.toLowerCase(Locale.getDefault());
        // MIME Typeを返す
        return MimeTypeMap.getSingleton().getMimeTypeFromExtension(ext);
    } else {
        // 拡張子が見つからない
        return null;
    }
}
 
Example #3
Source File: FileProvider.java    From attach with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Returns the MIME type of a content URI returned by
 * {@link #getUriForFile(Context, String, File) getUriForFile()}.
 *
 * @param uri A content URI returned by
 * {@link #getUriForFile(Context, String, File) getUriForFile()}.
 * @return If the associated file has an extension, the MIME type associated with that
 * extension; otherwise <code>application/octet-stream</code>.
 */
@Override
public String getType(Uri uri) {
    // ContentProvider has already checked granted permissions
    final File file = mStrategy.getFileForUri(uri);

    final int lastDot = file.getName().lastIndexOf('.');
    if (lastDot >= 0) {
        final String extension = file.getName().substring(lastDot + 1);
        final String mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
        if (mime != null) {
            return mime;
        }
    }

    return "application/octet-stream";
}
 
Example #4
Source File: CordovaResourceApi.java    From wildfly-samples with MIT License 6 votes vote down vote up
private String getMimeTypeFromPath(String path) {
    String extension = path;
    int lastDot = extension.lastIndexOf('.');
    if (lastDot != -1) {
        extension = extension.substring(lastDot + 1);
    }
    // Convert the URI string to lower case to ensure compatibility with MimeTypeMap (see CB-2185).
    extension = extension.toLowerCase(Locale.getDefault());
    if (extension.equals("3ga")) {
        return "audio/3gpp";
    } else if (extension.equals("js")) {
        // Missing from the map :(.
        return "text/javascript";
    }
    return MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
}
 
Example #5
Source File: LocalStorageProvider.java    From qiniu-lab-android with MIT License 6 votes vote down vote up
@Override
public String getDocumentType(final String documentId) throws FileNotFoundException {
    File file = new File(documentId);
    if (file.isDirectory())
        return Document.MIME_TYPE_DIR;
    // From FileProvider.getType(Uri)
    final int lastDot = file.getName().lastIndexOf('.');
    if (lastDot >= 0) {
        final String extension = file.getName().substring(lastDot + 1);
        final String mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
        if (mime != null) {
            return mime;
        }
    }
    return "application/octet-stream";
}
 
Example #6
Source File: LocalStorageProvider.java    From secrecy with Apache License 2.0 6 votes vote down vote up
@Override
public String getDocumentType(final String documentId) throws FileNotFoundException {
    File file = new File(documentId);
    if (file.isDirectory())
        return Document.MIME_TYPE_DIR;
    // From FileProvider.getType(Uri)
    final int lastDot = file.getName().lastIndexOf('.');
    if (lastDot >= 0) {
        final String extension = file.getName().substring(lastDot + 1);
        final String mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
        if (mime != null) {
            return mime;
        }
    }
    return "application/octet-stream";
}
 
Example #7
Source File: CordovaResourceApi.java    From cordova-plugin-intent with MIT License 6 votes vote down vote up
private String getMimeTypeFromPath(String path) {
    String extension = path;
    int lastDot = extension.lastIndexOf('.');
    if (lastDot != -1) {
        extension = extension.substring(lastDot + 1);
    }
    // Convert the URI string to lower case to ensure compatibility with MimeTypeMap (see CB-2185).
    extension = extension.toLowerCase(Locale.getDefault());
    if (extension.equals("3ga")) {
        return "audio/3gpp";
    } else if (extension.equals("js")) {
        // Missing from the map :(.
        return "text/javascript";
    }
    return MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
}
 
Example #8
Source File: MainActivity.java    From VBrowser-Android with GNU General Public License v2.0 6 votes vote down vote up
@Override
public boolean shouldOverrideUrlLoading(XWalkView view, String url) {
    if (!(url.startsWith("http") || url.startsWith("https"))) {
        //非http https协议 不动作
        return true;
    }

    //http https协议 在本webView中加载

    String extension = MimeTypeMap.getFileExtensionFromUrl(url);
    if(VideoFormatUtil.containsVideoExtension(extension)){
        detectedTaskUrlQueue.add(new DetectedVideoInfo(url,currentUrl,currentTitle));
        Log.d("MainActivity", "shouldOverrideUrlLoading detectTaskUrlList.add(url):" + url);
        return true;
    }

    Log.d("MainActivity", "shouldOverrideUrlLoading url="+url);
    view.loadUrl(url);
    return true;
}
 
Example #9
Source File: DocumentArchive.java    From FireFiles with Apache License 2.0 6 votes vote down vote up
private String getMimeTypeForEntry(ZipEntry entry) {
    if (entry.isDirectory()) {
        return Document.MIME_TYPE_DIR;
    }

    final int lastDot = entry.getName().lastIndexOf('.');
    if (lastDot >= 0) {
        final String extension = entry.getName().substring(lastDot + 1).toLowerCase(Locale.US);
        final String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
        if (mimeType != null) {
            return mimeType;
        }
    }

    return BASIC_MIME_TYPE;
}
 
Example #10
Source File: CordovaResourceApi.java    From countly-sdk-cordova with MIT License 6 votes vote down vote up
private String getMimeTypeFromPath(String path) {
    String extension = path;
    int lastDot = extension.lastIndexOf('.');
    if (lastDot != -1) {
        extension = extension.substring(lastDot + 1);
    }
    // Convert the URI string to lower case to ensure compatibility with MimeTypeMap (see CB-2185).
    extension = extension.toLowerCase(Locale.getDefault());
    if (extension.equals("3ga")) {
        return "audio/3gpp";
    } else if (extension.equals("js")) {
        // Missing from the map :(.
        return "text/javascript";
    }
    return MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
}
 
Example #11
Source File: CordovaResourceApi.java    From reader with MIT License 6 votes vote down vote up
private String getMimeTypeFromPath(String path) {
    String extension = path;
    int lastDot = extension.lastIndexOf('.');
    if (lastDot != -1) {
        extension = extension.substring(lastDot + 1);
    }
    // Convert the URI string to lower case to ensure compatibility with MimeTypeMap (see CB-2185).
    extension = extension.toLowerCase(Locale.getDefault());
    if (extension.equals("3ga")) {
        return "audio/3gpp";
    } else if (extension.equals("js")) {
        // Missing from the map :(.
        return "text/javascript";
    }
    return MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
}
 
Example #12
Source File: UploaderModule.java    From react-native-background-upload with MIT License 6 votes vote down vote up
@ReactMethod
public void getFileInfo(String path, final Promise promise) {
  try {
    WritableMap params = Arguments.createMap();
    File fileInfo = new File(path);
    params.putString("name", fileInfo.getName());
    if (!fileInfo.exists() || !fileInfo.isFile())
    {
      params.putBoolean("exists", false);
    }
    else
    {
      params.putBoolean("exists", true);
      params.putString("size",Long.toString(fileInfo.length())); //use string form of long because there is no putLong and converting to int results in a max size of 17.2 gb, which could happen.  Javascript will need to convert it to a number
      String extension = MimeTypeMap.getFileExtensionFromUrl(path);
      params.putString("extension",extension);
      String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension.toLowerCase());
      params.putString("mimeType", mimeType);
    }

    promise.resolve(params);
  } catch (Exception exc) {
    Log.e(TAG, exc.getMessage(), exc);
    promise.reject(exc);
  }
}
 
Example #13
Source File: DocumentArchive.java    From FireFiles with Apache License 2.0 6 votes vote down vote up
private String getMimeTypeForEntry(ZipEntry entry) {
    if (entry.isDirectory()) {
        return Document.MIME_TYPE_DIR;
    }

    final int lastDot = entry.getName().lastIndexOf('.');
    if (lastDot >= 0) {
        final String extension = entry.getName().substring(lastDot + 1).toLowerCase(Locale.US);
        final String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
        if (mimeType != null) {
            return mimeType;
        }
    }

    return BASIC_MIME_TYPE;
}
 
Example #14
Source File: CordovaResourceApi.java    From L.TileLayer.Cordova with MIT License 6 votes vote down vote up
private String getMimeTypeFromPath(String path) {
    String extension = path;
    int lastDot = extension.lastIndexOf('.');
    if (lastDot != -1) {
        extension = extension.substring(lastDot + 1);
    }
    // Convert the URI string to lower case to ensure compatibility with MimeTypeMap (see CB-2185).
    extension = extension.toLowerCase(Locale.getDefault());
    if (extension.equals("3ga")) {
        return "audio/3gpp";
    } else if (extension.equals("js")) {
        // Missing from the map :(.
        return "text/javascript";
    }
    return MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
}
 
Example #15
Source File: FileHelper.java    From crosswalk-cordova-android with Apache License 2.0 5 votes vote down vote up
public static String getMimeTypeForExtension(String path) {
    String extension = path;
    int lastDot = extension.lastIndexOf('.');
    if (lastDot != -1) {
        extension = extension.substring(lastDot + 1);
    }
    // Convert the URI string to lower case to ensure compatibility with MimeTypeMap (see CB-2185).
    extension = extension.toLowerCase(Locale.getDefault());
    if (extension.equals("3ga")) {
        return "audio/3gpp";
    }
    return MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
}
 
Example #16
Source File: ApplicationDcContext.java    From deltachat-android with GNU General Public License v3.0 5 votes vote down vote up
private String checkMime(String path, String mimeType) {
  if(mimeType == null || mimeType.equals("application/octet-stream")) {
    path = path.replaceAll(" ", "");
    String extension = MimeTypeMap.getFileExtensionFromUrl(path);
    String newType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
    if(newType != null) return newType;
  }
  return mimeType;
}
 
Example #17
Source File: OFileManager.java    From framework with GNU Affero General Public License v3.0 5 votes vote down vote up
public OValues getURIDetails(Uri uri) {
    OValues values = new OValues();
    ContentResolver mCR = mActivity.getContentResolver();
    if (uri.getScheme().equals("content")) {
        Cursor cr = mCR.query(uri, null, null, null, null);
        int nameIndex = cr.getColumnIndex(OpenableColumns.DISPLAY_NAME);
        int fileSize = cr.getColumnIndex(OpenableColumns.SIZE);
        if (cr.moveToFirst()) {
            values.put("name", cr.getString(nameIndex));
            values.put("datas_fname", values.get("name"));
            values.put("file_size", Long.toString(cr.getLong(fileSize)));
            String path = getPath(uri);
            if (path != null) {
                values.put("file_size", new File(path).length() + "");
            }
        }
        cr.close();
    }
    if (uri.getScheme().equals("file")) {
        File file = new File(uri.toString());
        values.put("name", file.getName());
        values.put("datas_fname", values.get("name"));
        values.put("file_size", Long.toString(file.length()));
    }
    values.put("file_uri", uri.toString());
    values.put("scheme", uri.getScheme());
    MimeTypeMap mime = MimeTypeMap.getSingleton();
    String type = mime.getMimeTypeFromExtension(mime
            .getExtensionFromMimeType(mCR.getType(uri)));
    values.put("file_type", (type == null) ? uri.getScheme() : type);
    values.put("type", type);
    return values;
}
 
Example #18
Source File: MarkDownProvider.java    From mvvm-template with GNU General Public License v3.0 5 votes vote down vote up
public static boolean isMarkdown(@Nullable String name) {
    if (InputHelper.isEmpty(name)) return false;
    name = name.toLowerCase();
    for (String value : MARKDOWN_EXTENSIONS) {
        String extension = MimeTypeMap.getFileExtensionFromUrl(name);
        if ((extension != null && value.replace(".", "").equals(extension)) ||
                name.equalsIgnoreCase("README") || name.endsWith(value))
            return true;
    }
    return false;
}
 
Example #19
Source File: ViewerViewModel.java    From mvvm-template with GNU General Public License v3.0 5 votes vote down vote up
public void onLoadContentAsStream() {
    boolean isImage = MarkDownProvider.isImage(url) && !"svg".equalsIgnoreCase(MimeTypeMap.getFileExtensionFromUrl(url));
    if (isImage || MarkDownProvider.isArchive(url)) {
        return;
    }
    execute(true, repoService.getFileAsStream(url),
            body -> {
                downloadedStream = body;
                code.setValue(downloadedStream);
            });
}
 
Example #20
Source File: DownloadStorageProvider.java    From FireFiles with Apache License 2.0 5 votes vote down vote up
/**
 * Add file extension to name, but only if exact MIME type mapping exists.
 */
private static String addExtension(String mimeType, String name) {
    final String extension = MimeTypeMap.getSingleton()
            .getExtensionFromMimeType(mimeType);
    if (extension != null) {
        return name + "." + extension;
    }
    return name;
}
 
Example #21
Source File: ShareUtils.java    From Gallery-example with GNU General Public License v3.0 5 votes vote down vote up
static void shareFile(Activity activity, String url) {
    try {
        File myFile = new File(url);
        MimeTypeMap mime = MimeTypeMap.getSingleton();
        String ext = myFile.getName().substring(myFile.getName().lastIndexOf(".") + 1);
        String type = mime.getMimeTypeFromExtension(ext);
        Intent sharingIntent = new Intent("android.intent.action.SEND");
        sharingIntent.setType(type);
        sharingIntent.putExtra("android.intent.extra.STREAM", Uri.fromFile(myFile));
        activity.startActivity(Intent.createChooser(sharingIntent, activity.getString(R.string.shareWith)));
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example #22
Source File: FileHelper.java    From reader with MIT License 5 votes vote down vote up
public static String getMimeTypeForExtension(String path) {
    String extension = path;
    int lastDot = extension.lastIndexOf('.');
    if (lastDot != -1) {
        extension = extension.substring(lastDot + 1);
    }
    // Convert the URI string to lower case to ensure compatibility with MimeTypeMap (see CB-2185).
    extension = extension.toLowerCase(Locale.getDefault());
    if (extension.equals("3ga")) {
        return "audio/3gpp";
    }
    return MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
}
 
Example #23
Source File: FileUtils.java    From AndroidDownload with Apache License 2.0 5 votes vote down vote up
/**
 * 获取文件的MIME类型
 */
public static String getMimeType(String pathOrUrl) {
    String ext = getExtension(pathOrUrl);
    MimeTypeMap map = MimeTypeMap.getSingleton();
    String mimeType;
    if (map.hasExtension(ext)) {
        mimeType = map.getMimeTypeFromExtension(ext);
    } else {
        mimeType = "*/*";
    }
    return mimeType;
}
 
Example #24
Source File: DownloadReceiver.java    From 4pdaClient-plus with Apache License 2.0 5 votes vote down vote up
private Intent getRunFileIntent(String filePath) {
    MimeTypeMap myMime = MimeTypeMap.getSingleton();
    Intent newIntent = new Intent(Intent.ACTION_VIEW);
    String mimeType = myMime.getMimeTypeFromExtension(FileUtils.fileExt(filePath).substring(1));
    newIntent.setDataAndType(Uri.parse("file://" + filePath), mimeType);
    newIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    return newIntent;
}
 
Example #25
Source File: FileUtils.java    From FireFiles with Apache License 2.0 5 votes vote down vote up
/**
 * Remove file extension from name, but only if exact MIME type mapping
 * exists. This means we can reapply the extension later.
 */
public static String removeExtension(String mimeType, String name) {
    final int lastDot = name.lastIndexOf('.');
    if (lastDot >= 0) {
        final String extension = name.substring(lastDot + 1).toLowerCase();
        final String nameMime = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
        if (mimeType.equals(nameMime)) {
            return name.substring(0, lastDot);
        }
    }
    return name;
}
 
Example #26
Source File: TaskDetailActivity.java    From Kandroid with GNU General Public License v3.0 5 votes vote down vote up
@Override
        public void onDownloadTaskFile(boolean success, int id, String data) {
            if (success) {
                byte[] inData = Base64.decode(data, Base64.DEFAULT);
                for (KanboardTaskFile f: files) {
                    if (f.getId() == id) {
                        try {
                            File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), f.getName());
                            FileOutputStream outData = new FileOutputStream(file);
                            outData.write(inData);
                            outData.close();
                            String mime = MimeTypeMap.getSingleton().getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(file).toString()));
                            if (mime == null) {
                                mime = "application/octet-stream";
                            }
                            if (BuildConfig.DEBUG) {
                                Log.d(Constants.TAG, Uri.fromFile(file).toString());
                                Log.d(Constants.TAG, mime);
                            }
                            DownloadManager dm = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
                            dm.addCompletedDownload(file.getName(), "Kandroid download", false, mime, file.getPath(), file.length(), true);
//                            Snackbar.make(findViewById(R.id.root_layout), String.format(Locale.getDefault(), "Saved file to: %s", file.getPath()), Snackbar.LENGTH_LONG).show();
                        } catch (IOException e) {
                            Log.w(Constants.TAG, "IOError writing file");
                            e.printStackTrace();
                        }
                        break;
                    }
                }
            } else {
                Snackbar.make(findViewById(R.id.root_layout), "Unable to download file", Snackbar.LENGTH_LONG).show();
            }
        }
 
Example #27
Source File: DownloadStorageProvider.java    From FireFiles with Apache License 2.0 5 votes vote down vote up
/**
 * Add file extension to name, but only if exact MIME type mapping exists.
 */
private static String addExtension(String mimeType, String name) {
    final String extension = MimeTypeMap.getSingleton()
            .getExtensionFromMimeType(mimeType);
    if (extension != null) {
        return name + "." + extension;
    }
    return name;
}
 
Example #28
Source File: Utils.java    From MoeGallery with GNU General Public License v3.0 5 votes vote down vote up
public static String getMimeType(String url) {
    String type;
    String extension = url.substring(url.lastIndexOf('.') + 1);
    MimeTypeMap mime = MimeTypeMap.getSingleton();
    type = mime.getMimeTypeFromExtension(extension);
    return type;
}
 
Example #29
Source File: ConsoleContentProvider.java    From matrix-android-console with Apache License 2.0 5 votes vote down vote up
@Override
public String getType(Uri arg0) {
    String type = null;
    String extension = MimeTypeMap.getFileExtensionFromUrl(arg0.toString());
    if (extension != null) {
        MimeTypeMap mime = MimeTypeMap.getSingleton();
        type = mime.getMimeTypeFromExtension(extension);
    }

    return type;
}
 
Example #30
Source File: SpiderQueen.java    From EhViewer with Apache License 2.0 5 votes vote down vote up
@Nullable
public UniFile save(int index, @NonNull UniFile dir, @NonNull String filename) {
    int state = getPageState(index);
    if (STATE_FINISHED != state) {
        return null;
    }

    InputStreamPipe pipe = mSpiderDen.openInputStreamPipe(index);
    if (null == pipe) {
        return null;
    }

    OutputStream os = null;
    try {
        pipe.obtain();

        // Get dst file
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeStream(pipe.open(), null, options);
        pipe.close();
        String extension = MimeTypeMap.getSingleton().getExtensionFromMimeType(options.outMimeType);
        UniFile dst = dir.subFile(null != extension ? filename + "." + extension : filename);
        if (null == dst) {
            return null;
        }

        // Copy
        os = dst.openOutputStream();
        IOUtils.copy(pipe.open(), os);
        return dst;
    } catch (IOException e) {
        return null;
    } finally {
        pipe.close();
        pipe.release();
        IOUtils.closeQuietly(os);
    }
}