多文件上传--3 (uploadImage.swf)



源代码下载地址:

http://download.youkuaiyun.com/detail/vincent_void/4632113


本篇同二《多文件上传--2 uploadImage.swf》相比,只是增加了一个限制文件大小的功能。


页面引用代码如下所示:

    <div id="myContent">
    </div>
    <input type="hidden" id="IsUpload" value="" />
    <script type="text/javascript">
        window.onload = function () {
            var params = {
                uploadServerUrl: "upload.aspx", //上传响应页面(必须设置)
                maxFileData: 1024 * 300,       //300KB
                jsFunction: "upload",         //上传成功后回调JS
                filter: "*.jpg;"        //上传文件类型限制
            }
            swfobject.embedSWF("ImageFlashUpload/flash/uploadImage.swf", "myContent", "600", "500", "10.0.0", "ImageFlashUpload/flash/expressInstall.swf", params);
        }

        function upload() {

        }
    </script>


upload.aspx 后台处理代码如下:

 protected void Page_Load(object sender, EventArgs e)
    {
        ImgSave();
    }
  
    /// <summary>
    /// 批量上传
    /// </summary>
    public void ImgSave()
    {

        HttpFileCollection files = Request.Files;

        if (files.Count == 0)
        {
            Response.Write("请勿直接访问本文件");
            Response.End();
        }
        
    
        string CorpImg = "~/images/" + DateTime.Now.ToString("yyyyMMdd") + "/";
        string path = Server.MapPath(CorpImg); //"~/AdminUpload/Image/"
        //如果目录不存在,则创建
        if (!Directory.Exists(path)) Directory.CreateDirectory(path);
       
        // 只取第 1 个文件
        HttpPostedFile file = files[0];
        if (file != null && file.ContentLength > 0)
        {
            // flash 会自动发送文件名到 Request.Form["fileName"]
            #region 保存原始图片

            string fileName =  DateTime.Now.ToString("yyyyMMddHHmmssfff") + Path.GetExtension(Request.Form["fileName"]);  //文件名
            string savePath = path + "\\" + fileName;
            file.SaveAs(savePath);

            #endregion

        }

    }


多文件上传--2 (uploadImage.swf) 地址:http://blog.youkuaiyun.com/vincent_void/article/details/7902734


如有侵犯别人的著作权,请留言,我会关闭相关内容!

[ { "name": "mmexport1753757872962.jpg", "uri": "content://com.android.externalstorage.documents/tree/primary%3A%E4%BD%A0%E5%A5%BD%2F%E6%96%87%E4%BB%B6%E5%A4%B91%2Fmmexport1753757872962.jpg", "isDirectory": false, "isFile": true, "realPath": "/tree/primary:你好/文件夹1/mmexport1753757872962.jpg/document/primary:你好/文件夹1/mmexport1753757872962.jpg" }, { "name": "Screenshot_2025-07-29-10-57-28-907_com.tencent.mm.jpg", "uri": "content://com.android.externalstorage.documents/tree/primary%3A%E4%BD%A0%E5%A5%BD%2F%E6%96%87%E4%BB%B6%E5%A4%B91%2FScreenshot_2025-07-29-10-57-28-907_com.tencent.mm.jpg", "isDirectory": false, "isFile": true, "realPath": "/tree/primary:你好/文件夹1/Screenshot_2025-07-29-10-57-28-907_com.tencent.mm.jpg/document/primary:你好/文件夹1/Screenshot_2025-07-29-10-57-28-907_com.tencent.mm.jpg" }, { "name": "Screenshot_2025-07-29-10-57-23-824_com.tencent.mm.jpg", "uri": "content://com.android.externalstorage.documents/tree/primary%3A%E4%BD%A0%E5%A5%BD%2F%E6%96%87%E4%BB%B6%E5%A4%B91%2FScreenshot_2025-07-29-10-57-23-824_com.tencent.mm.jpg", "isDirectory": false, "isFile": true, "realPath": "/tree/primary:你好/文件夹1/Screenshot_2025-07-29-10-57-23-824_com.tencent.mm.jpg/document/primary:你好/文件夹1/Screenshot_2025-07-29-10-57-23-824_com.tencent.mm.jpg" }, { "name": "Screenshot_2025-07-29-10-57-19-319_com.tencent.mm.jpg", "uri": "content://com.android.externalstorage.documents/tree/primary%3A%E4%BD%A0%E5%A5%BD%2F%E6%96%87%E4%BB%B6%E5%A4%B91%2FScreenshot_2025-07-29-10-57-19-319_com.tencent.mm.jpg", "isDirectory": false, "isFile": true, "realPath": "/tree/primary:你好/文件夹1/Screenshot_2025-07-29-10-57-19-319_com.tencent.mm.jpg/document/primary:你好/文件夹1/Screenshot_2025-07-29-10-57-19-319_com.tencent.mm.jpg" } ]
最新发布
08-03
<think>我们正在讨论的是在Android平台上,如何获取图片文件列表及其URI路径,并可能进行进一步处理(如显示、上传等)。根据引用内容,我们可以总结出几个关键点: 1. **获取图片URI**:通过启动系统的相册或文件选择器(使用`Intent.ACTION_GET_CONTENT`)并处理`onActivityResult`回调来获取图片的URI(引用[3])。 2. **将URI转换为绝对路径**:在`onActivityResult`中获取到URI后,需要将其转换为绝对路径(引用[1])。 3. **通过URI获取Bitmap**:有时我们可能需要直接获取Bitmap对象(引用[2]),例如用于显示或压缩。 另外,引用[4]展示了通过反射获取系统属性,但此问题中可能不直接相关。 ### 步骤1:获取图片列表(启动系统相册或文件选择器) 在Android中,我们可以使用Intent来启动系统相册或文件选择器,让用户选择图片。设置Intent的action为`Intent.ACTION_GET_CONTENT`,类型为图片类型(如"image/*")。 ### 步骤2:在onActivityResult中获取URI 当用户选择图片后,系统会回调`onActivityResult`方法,我们可以从返回的Intent中获取到图片的URI。 ### 步骤3:将URI转换为绝对路径 由于Android系统的安全机制,直接获取的URI可能是`content://`形式,我们需要将其转换为文件的绝对路径(如果可能)或者直接读取文件内容。 ### 步骤4:进一步处理 获取到绝对路径或Bitmap后,可以进行显示、上传、压缩等操作。 ### 代码实现 #### 1. 启动图片选择 ```java private static final int REQUEST_CODE_PICK_IMAGE = 1001; private void pickImage() { Intent intent = new Intent(Intent.ACTION_GET_CONTENT); intent.setType("image/*"); startActivityForResult(intent, REQUEST_CODE_PICK_IMAGE); } ``` #### 2. 处理选择结果 在`onActivityResult`中: ```java @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == REQUEST_CODE_PICK_IMAGE && resultCode == RESULT_OK) { if (data != null) { Uri uri = data.getData(); // 获取绝对路径 String absolutePath = getAbsolutePath(this, uri); Log.d("ImagePath", "Absolute Path: " + absolutePath); // 或者直接获取Bitmap try { Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri); // 处理bitmap,例如显示在ImageView上 imageView.setImageBitmap(bitmap); } catch (IOException e) { e.printStackTrace(); } } } } ``` #### 3. 将URI转换为绝对路径的方法 根据引用[1],我们可以通过ContentResolver查询来获取绝对路径。但是注意,由于Android不同版本的变化,这种方法可能不是对所有URI都有效。以下是一个常用的方法: ```java public String getAbsolutePath(Context context, Uri uri) { String absolutePath = null; String[] projection = {MediaStore.Images.Media.DATA}; Cursor cursor = context.getContentResolver().query(uri, projection, null, null, null); if (cursor != null) { int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); cursor.moveToFirst(); absolutePath = cursor.getString(column_index); cursor.close(); } return absolutePath; } ``` **注意**:这种方法适用于`MediaStore`类型的URI,但对于其他类型的URI(如来自文件管理器或云存储的URI)可能无效。对于Android 10及以上版本,由于作用域存储(Scoped Storage)的限制,获取绝对路径变得更为复杂,可能需要使用`ContentResolver`打开输入流来读取文件内容,并将内容写入应用自己的缓存目录中。 ### 处理高版本Android(Scoped Storage) 在Android 10(API 29)及以上,推荐使用`ContentResolver`打开输入流,然后读取文件内容,而不是尝试获取绝对路径。我们可以将文件内容读取到应用的私有目录中,然后使用该文件。 ```java private String copyFileToInternalStorage(Context context, Uri uri, String dirName) { File dir = context.getDir(dirName, Context.MODE_PRIVATE); File file = new File(dir, "temp_image.jpg"); try (InputStream inputStream = context.getContentResolver().openInputStream(uri); FileOutputStream outputStream = new FileOutputStream(file)) { byte[] buffer = new byte[4 * 1024]; // 4KB buffer int bytesRead; while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } outputStream.flush(); return file.getAbsolutePath(); } catch (Exception e) { e.printStackTrace(); } return null; } ``` 在`onActivityResult`中,我们可以这样使用: ```java String internalPath = copyFileToInternalStorage(this, uri, "images"); if (internalPath != null) { // 使用内部路径 File imageFile = new File(internalPath); // 或者加载为Bitmap Bitmap bitmap = BitmapFactory.decodeFile(internalPath); } ``` ### 总结 1. 使用`Intent.ACTION_GET_CONTENT`启动图片选择器。 2. 在`onActivityResult`中获取URI。 3. 将URI转换为可用的文件路径(根据Android版本选择合适的方法)或直接获取Bitmap。 4. 对于高版本Android,避免直接获取绝对路径,而是将文件内容复制到应用私有目录。 ### 相关问题 1. 在Android高版本(API 29及以上)中如何安全地访问相册图片? 2. 如何压缩从相册选择的图片? 3. 如何同时选择多张图片并获取它们的URI?</think>在 Android 开发中,获取图片文件列表及其 URI 路径并处理图片数据是一个常见需求。以下是完整的实现方案,包含获取图片 URI、转换为本地路径以及处理图片数据的步骤: --- ### 1. 启动系统相册获取图片 URI 使用 `Intent.ACTION_GET_CONTENT` 启动系统相册选择图片: ```java private static final int PICK_IMAGE_REQUEST = 1001; private static final String IMAGE_TYPE = "image/*"; // 启动相册选择 private void openGallery() { Intent intent = new Intent(Intent.ACTION_GET_CONTENT); intent.setType(IMAGE_TYPE); startActivityForResult(intent, PICK_IMAGE_REQUEST); } ``` --- ### 2. 在 onActivityResult 中获取 URI 处理选择结果并获取图片 URI: ```java @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null) { Uri imageUri = data.getData(); String absolutePath = getAbsolutePath(this, imageUri); // 转换为绝对路径 // 处理图片数据 processImage(absolutePath); } } ``` --- ### 3. 将 URI 转换为绝对路径 核心转换方法(兼容 Android 4.4+): ```java public String getAbsolutePath(Context context, Uri uri) { if (uri == null) return null; // 检查是否为文件 URI (file://) if (ContentResolver.SCHEME_FILE.equals(uri.getScheme())) { return uri.getPath(); } // 处理 Content URI (content://) String[] projection = {MediaStore.Images.Media.DATA}; Cursor cursor = null; try { cursor = context.getContentResolver().query( uri, projection, null, null, null ); if (cursor != null && cursor.moveToFirst()) { int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA); return cursor.getString(columnIndex); } } catch (Exception e) { Log.e("URI_Convert", "Error converting URI: " + e.getMessage()); } finally { if (cursor != null) cursor.close(); } // 备用方案:直接读取文件流 return copyFileToCache(context, uri); } ``` --- ### 4. 处理无法直接转换的 URI(Android 10+) 对于 Android 10(API 29+)的 Scoped Storage,使用缓存方案: ```java private String copyFileToCache(Context context, Uri uri) { File cacheDir = context.getCacheDir(); String fileName = "img_" + System.currentTimeMillis() + ".tmp"; File outputFile = new File(cacheDir, fileName); try (InputStream in = context.getContentResolver().openInputStream(uri); OutputStream out = new FileOutputStream(outputFile)) { byte[] buf = new byte[1024]; int len; while ((len = in.read(buf)) > 0) { out.write(buf, 0, len); } return outputFile.getAbsolutePath(); } catch (IOException e) { Log.e("FileCopy", "Error copying file: " + e.getMessage()); return null; } } ``` --- ### 5. 图片数据处理示例 #### A. 获取 Bitmap 并压缩 ```java private void processImage(String absolutePath) { // 获取 Bitmap Bitmap originalBitmap = BitmapFactory.decodeFile(absolutePath); // 压缩图片(质量压缩) ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); originalBitmap.compress(Bitmap.CompressFormat.JPEG, 70, outputStream); byte[] compressedData = outputStream.toByteArray(); // 使用压缩后的数据 uploadImage(compressedData); } ``` #### B. 获取图片信息 ```java private void getImageInfo(String absolutePath) { File imageFile = new File(absolutePath); String info = "Name: " + imageFile.getName() + "\n" + "Size: " + (imageFile.length() / 1024) + " KB\n" + "Path: " + absolutePath; // 显示信息或上传 Log.d("ImageInfo", info); } ``` --- ### 关键注意事项 1. **权限声明**(AndroidManifest.xml): ```xml <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> ``` 对于 Android 13+ 需要添加: ```xml <uses-permission android:name="android.permission.READ_MEDIA_IMAGES" /> ``` 2. **Android 10+ 适配**: - 使用 `Context.getCacheDir()` 避免存储权限问题 - 优先使用 `ContentResolver` 直接操作 URI - 大文件处理建议在后台线程执行 3. **性能优化**: ```java // 使用采样率加载大图 BitmapFactory.Options options = new BitmapFactory.Options(); options.inSampleSize = 4; // 缩小4倍 Bitmap sampledBitmap = BitmapFactory.decodeFile(path, options); ``` --- ### 相关问题 1. 如何在 Android 10+ 中安全地访问相册图片? 2. 如何实现多张图片选择并批量处理? 3. 图片压缩的最佳实践有哪些(质量 vs 尺寸压缩)? 4. 如何将图片 URI 转换为 Base64 字符串? 5. Android 中如何获取图片的 EXIF 信息(如拍摄方向)? > 引用说明: > [^1]: 通过 ContentResolver 查询 MediaStore 获取绝对路径的实现方法 > [^2]: 使用 `MediaStore.Images.Media.getBitmap` 直接获取 Bitmap > [^3]: 启动系统相册的标准 Intent 构造方式 > [^4]: 系统级属性获取的反射技术(虽不直接相关但提供系统交互思路)
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值