# 18.2:打开相册上传图片

APP 开发过程中,会有上传图片的需求,比如用户设置头像,一般都是打开相册,选择相应图片,然后上传服务器,本节简单讲解一下打开相册和上传服务器的操作。

# 18.2.1:客户端选择图片

ArkUI 开发框架在 @ohos.multimedia.mediaLibrary 库中提供了打开相册的方法,该方法的回调参数里会返回选取的所有图片地址,地址格式是:dataability:///media/external/images/media/***,打开相册的过程如下:

  • 引入 mediaLibrary 库

    import mediaLibrary from '@ohos.multimedia.mediaLibrary';
    
    1
  • 打开相册

    // 打开相册,调用startMediaSelect()方法
    private openGallery() {
      let option: mediaLibrary.MediaSelectOption = {
        type: "media", // 选取视屏和图片
        count: 1000
      }
    
      mediaLibrary.getMediaLibrary().startMediaSelect(option, (error, result) => {
        if (result) {
          result.forEach((value) => {
            console.log("value: " + value)
          })
        } else {
          console.log("error: " + JSON.stringify(error))
        }
      });
    }
    
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17

    openGallery() 方法打开相册调用的是 startMediaSelect() 方法,startMediaSelect() 方法的回调参数 result 是一个数组,它是在相册里选取的所有图片地址集合,openGallery() 方法运行后打印日志如下:

    JSApp: app Log: path: dataability:///media/external/images/media/4345
    JSApp: app Log: path: dataability:///media/external/images/media/4339
    
    1
    2

    📢:MediaSelectOptiontype 如果设置成 media,则 startMediaSelect() 方法返回的数据无法区分是图片还是视频。

# 18.2.2:客户端上传图片

笔者在第 12 章 第 3 小节 介绍过文件上传的操作,读者可自行前往阅读,这里就直接复用之前的代码,如下所示:

private uploadImages(paths: string[]) {
  var allFiles = Array<request.File>()
  for (var i = 0; i <paths.length; i++) {
    var path = paths[i]
    console.log("path: " + path)
    allFiles[i] = {
      name: "image" + i + ".jpg",
      filename: "image" + i + ".jpg",
      uri: path,
      type: "image"
    }
  }
  request.upload({
    url: "http://192.168.1.5:8080/java_0101_fileupload_war_exploded/uploadServlet",
    method: "POST",
    files: allFiles,
    header: {},
    data: [
      {
        name: "test",
        value: "value"
      }
    ]
  }, (error, response) => {
    if(response) {
      response.on('progress', (uploadedSize: number, totalSize: number) => {
        console.log("progress, uploadedSize: " + uploadedSize + ", totalSize: " + totalSize)
      })
    } else {
      console.log("upload failure: " + error)
    }
  });
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33

uploadImages() 方法的参数 paths 是打开相册后返回的所选图片路径,考虑到多文件场景,笔者把所有路径都封装在 allFiles 中,最后调用 requestupload 方法做文件上传,执行该方法,打印日志如下所示:

JSApp: app Log: progress, uploadedSize: 81920,  totalSize: 342248
JSApp: app Log: progress, uploadedSize: 163840, totalSize: 342248
JSApp: app Log: progress, uploadedSize: 177941, totalSize: 342248
JSApp: app Log: progress, uploadedSize: 259861, totalSize: 342248
JSApp: app Log: progress, uploadedSize: 341781, totalSize: 342248
JSApp: app Log: progress, uploadedSize: 342248, totalSize: 342248
1
2
3
4
5
6

# 18.2.3:客户端完整样例

客户端选择图片并上传服务器的完整样例如下所示:

import mediaLibrary from '@ohos.multimedia.mediaLibrary';
import request from '@ohos.request';

@Entry @Component struct Index {

  build() {
    Column({space: 10}) {
      Button("打开相册")
        .onClick(() => {
          this.openGallery()
        })
    }
    .width('100%')
    .height('100%')
    .padding(10)
  }

  private openGallery() {
    let option: mediaLibrary.MediaSelectOption = {
      type: "media",
      count: 1000
    }
    mediaLibrary.getMediaLibrary().startMediaSelect(option, (error, result) => {
      if (result) {
        this.uploadImage(result)
      } else {
        console.log("error: " + JSON.stringify(error))
      }
    });
  }

  private uploadImage(paths: string[]) {
    var allFiles = Array<request.File>()
    for (var i = 0; i <paths.length; i++) {
      var path = paths[i]
      console.log("path: " + path)
      allFiles[i] = {
        name: "image" + i + ".jpg",
        filename: "image" + i + ".jpg",
        uri: path,
        type: "image"
      }
    }
    request.upload({
      url: "http://192.168.1.5:8080/java_0101_fileupload_war_exploded/uploadServlet",
      method: "POST",
      files: allFiles,
      header: {},
      data: [
        {
          name: "test",
          value: "value"
        }
      ]
    }, (error, response) => {
      if(response) {
        response.on('progress', (uploadedSize: number, totalSize: number) => {
          console.log("progress, uploadedSize: " + uploadedSize + ", totalSize: " + totalSize)
        })
      } else {
        console.log("upload failure: " + error)
      }
    });
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65

# 18.2.4:服务器接收图片

服务器接收客户端的数据,笔者为了简单演示,使用了 Servlet + fileupload 的方式,服务端样例代码如下:

@WebServlet(name = "uploadServlet", value = "/uploadServlet")
public class UploadServlet extends HttpServlet {

    private static final String CHARSET = "UTF-8";

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding(CHARSET);
        if (ServletFileUpload.isMultipartContent(req)) {
            File tempFile = new File(req.getSession().getServletContext().getRealPath("/") + "temp");
            if (!tempFile.exists()) tempFile.mkdirs();

            DiskFileItemFactory factory = new DiskFileItemFactory();
            factory.setSizeThreshold(1024 * 1024 * 10);
            factory.setRepository(tempFile);

            ServletFileUpload upload = new ServletFileUpload(factory);
            upload.setHeaderEncoding(CHARSET);

            File uploadFile = new File(req.getSession().getServletContext().getRealPath("/") + "upload");
            if (!uploadFile.exists()) uploadFile.mkdirs();

            try {
                List<FileItem> fileItems =  upload.parseRequest(req);
                for (FileItem item : fileItems) {
                    if (item.isFormField()) {
                        String name = item.getFieldName();
                        String value = item.getString(CHARSET);
                        System.out.println("name: " + name + ", value: " + value);
                    } else {
                        String fileName = item.getName();
                        File file = new File(uploadFile, fileName);
                        item.write(file);
                        System.out.println(fileName + ", file length: " + file.length());
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        // doResponse(req, resp);
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44

客户端点击上传图片后,服务器端接收到请求,打印日志如下:

name: test, value: value
image0.jpg, file length: 177941
image1.jpg, file length: 164308
1
2
3

然后在服务器相应工程目录下的 upload 文件夹中就可以看到我们上传的文件了,截图如下所示:

18_2_4_1

# 18.2.5:小结

以上就是笔者讲述的打开相册上传图片的完整样例供读者参考,也非常欢迎读者给本网站提供更多的开发样例。

(adsbygoogle = window.adsbygoogle || []).push({});
请作者喝杯咖啡

津公网安备 12011402001367号

津ICP备2020008934号-2

中央网信办互联网违法和不良信息举报中心

天津市互联网违法和不良信息举报中心