uniapp api下载和上传图片

1.下载图片 

<template>
  <view class="container">
    <image v-if="imagePath" :src="imagePath" mode="widthFix"></image>
    <button @click="downloadImage">下载图片</button>
  </view>
</template>

<script>
export default {
  data() {
    return {
      imagePath: '', // 用于存储下载的图片路径
    };
  },
  methods: {
    downloadImage() {
      uni.downloadFile({
        url: 'http://localhost:5000/get', // Flask服务器的URL
        header: {
          'Authorization': 'Bearer 123456' // 设置请求头以通过服务器的授权检查
        },
        success: (downloadRes) => {
          if (downloadRes.statusCode === 200) {
            this.imagePath = downloadRes.tempFilePath; // 设置图片路径为下载的文件路径
            uni.showToast({ title: '图片下载成功', icon: 'success' });
          } else {
            uni.showToast({ title: '下载失败:无效的状态码', icon: 'none' });
          }
        },
        fail: (err) => {
          uni.showToast({ title: '下载失败', icon: 'none' });
          console.error('Download failed:', err);
        }
      });
    },
  },
};
</script>

<style scoped>
.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100vh;
}
button {
  margin-top: 20px;
}
</style>

2.上传图片

<template>
  <view class="container">
    <button @click="selectAndUploadImage">Upload Image</button>
    <text v-if="uploadStatus !== ''">{{ uploadStatus }}</text>
  </view>
</template>

<script>
export default {
  data() {
    return {
      uploadStatus: '',
    };
  },
  methods: {
    selectAndUploadImage() {
      uni.chooseImage({
        count: 1, // 默认9,这里设置为1表示只选择一张图片
        sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有
        sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有
        success: (res) => {
          // tempFilePath可以作为img标签的src属性显示图片,也可以用于上传等操作
          const tempFilePaths = res.tempFilePaths;
          this.uploadFile(tempFilePaths[0]); // 上传第一张图片
        },
      });
    },
    uploadFile(filePath) {
      const uploadTask = uni.uploadFile({
        url: 'http://localhost:5000/request', // Flask服务器的URL
        filePath: filePath,
        name: 'img', // 必须提供后台用来接收文件的字段名
        header: {
          // 添加 Authorization 请求头
          Authorization: 'Bearer 123456', // 替换为与后端一致的密钥
        },
        formData: {
          // 可以添加其他表单数据
        },
        success: (uploadFileRes) => {
          console.log(uploadFileRes);
          const response = JSON.parse(uploadFileRes.data); // 解析返回结果
          if (response.msg) {
            this.uploadStatus = response.msg; // 显示后端返回的消息
          } else {
            this.uploadStatus = '上传成功!';
          }
        },
        fail: (err) => {
          console.error(err);
          this.uploadStatus = 'Upload failed';
        },
      });

      uploadTask.onProgressUpdate((res) => {
        console.log('上传进度', res.progress);
        console.log('已经上传的数据长度', res.totalBytesSent);
        console.log('预期需要上传的数据总长度', res.totalBytesExpectedToSend);
      });
    },
  },
};
</script>

<style scoped>
.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100vh;
}
button {
  margin-bottom: 20px;
}
</style>

### UniApp 中实现图片上传与保存功能 #### 功能概述 在 UniApp 开发中,可以通过前端调用接口将用户选择的图片上传至服务端,并由服务端负责存储管理这些图片。以下是基于 UniApp SpringBoot 的具体实现方式。 --- #### 前端部分 (UniApp) ##### 用户选择图片上传 通过 `uni.chooseImage` 方法让用户从相册或相机获取图片,再利用 `uni.uploadFile` 将选中的图片发送给后端 API 接口。 ```javascript // 页面方法:选择图片上传 export default { methods: { uploadImage() { uni.chooseImage({ count: 1, // 只允许选择一张图片 sizeType: ['original', 'compressed'], // 可以指定原图或压缩图 sourceType: ['album', 'camera'], // 来源可以是相册或者相机 success(res) { const tempFilePaths = res.tempFilePaths; // 获取临时路径 if (tempFilePaths.length > 0) { const filePath = tempFilePaths[0]; // 调用上传函数 uni.uploadFile({ url: 'http://your-springboot-server/api/upload', // 替换为实际的服务端API地址 filePath: filePath, name: 'file', header: { 'Authorization': 'Bearer token' }, // 如果有鉴权需求,设置请求头 formData: {}, // 自定义参数 success(uploadRes) { console.log('Upload Success:', JSON.parse(uploadRes.data)); alert('图片上传成功!'); }, fail(err) { console.error('Upload Failed:', err); alert('图片上传失败,请稍后再试'); } }); } else { alert('未选择任何图片'); } }, fail(err) { console.error('Choose Image Error:', err); alert('选择图片失败,请稍后再试'); } }); } } } ``` 上述代码实现了用户选择图片并通过 HTTP 请求将其上传到服务器的功能[^1]。 --- #### 后端部分 (Spring Boot) ##### 图片接收与保存逻辑 在 Spring Boot 中创建一个控制器来处理文件上传请求,并将接收到的文件保存到指定目录。 ```java import org.springframework.web.bind.annotation.*; import org.springframework.web.multipart.MultipartFile; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; @RestController @RequestMapping("/api") public class FileController { private static final String UPLOAD_DIR = "E:/Data/uploadFile"; // 文件保存路径 @PostMapping("/upload") public ResponseEntity<String> handleFileUpload(@RequestParam("file") MultipartFile file) { try { if (!file.isEmpty()) { Path path = Paths.get(UPLOAD_DIR, file.getOriginalFilename()); Files.createDirectories(path.getParent()); // 创建父级目录(如果不存在) Files.write(path, file.getBytes()); // 写入文件 return ResponseEntity.ok("文件已成功上传:" + file.getOriginalFilename()); } else { return ResponseEntity.badRequest().body("上传的文件为空"); } } catch (IOException e) { e.printStackTrace(); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("文件上传失败:" + e.getMessage()); } } @GetMapping("/{filename}") public ResponseEntity<Resource> serveFile(@PathVariable String filename) throws IOException { Path filePath = Paths.get(UPLOAD_DIR, filename); Resource resource = new UrlResource(filePath.toUri()); if (resource.exists() || resource.isReadable()) { return ResponseEntity.ok() .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + resource.getFilename() + "\"") .contentType(MediaType.APPLICATION_OCTET_STREAM) .contentLength(resource.contentLength()) .body(resource); } else { throw new FileNotFoundException("无法找到文件:" + filename); } } } ``` 此代码片段展示了如何通过 Spring Boot 处理文件上传以及提供下载链接的功能[^3]。 --- #### 关键注意事项 1. **文件存储位置** - 不建议将文件存储在项目的 `resources/static` 或其他运行时不可变目录下,应使用独立的磁盘空间作为存储区域。 2. **安全性考虑** - 对于生产环境,需验证文件类型、大小等属性,防止恶意攻击者上传非法内容。 - 使用 JWT 或 OAuth 等机制保护 API 接口的安全性。 3. **跨域配置** - 若前后端分离部署,则需要在 Spring Boot 中启用 CORS 支持,以便客户端能够正常访问服务端资源。 --- #### 完整流程说明 - 用户触发按钮事件,在前端页面上执行 `chooseImage` 并返回所选图片的本地临时路径; - 利用 `uploadFile` 发起 POST 请求,携带二进制数据提交至服务端; - 在服务端解析 multipart/form-data 类型的数据流,提取目标文件对象; - 检查合法性之后写入硬盘上的特定目录完成持久化操作;最后反馈状态消息给前端显示结果提示信息[^2]。 --- ### 示例效果图 | 步骤 | 描述 | |------|------| | ![Step1](https://example.com/image-step1.png) | 打开应用界面,点击“上传”按钮启动交互过程。 | | ![Step2](https://example.com/image-step2.png) | 弹出选项菜单供用户决定是从摄像头拍摄还是浏览已有素材库选取素材。 | 以上便是完整的实现方案及其配套样例演示效果。 ---
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值