weixin_43186810 2024-06-08 15:41 采纳率: 30%
浏览 5
已结题

(标签-ui|关键词-app)

nuiapp
1、电脑端调试可以正常上传图片,但是在手机上调试或是安装在手机上都不能上传图片,
2、已经勾选相机

img

3、nuiapp的上传代码

// 调用拍照功能
    takePhoto() {
      // 调用uniapp API选择或拍照
      uni.chooseImage({
        count: 1, // 默认9, 设置图片的数量
        sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有 
        sourceType: ['camera', 'album'], // 可以指定来源是相册还是相机,默认二者都有
        success: (res) => {
          // 成功选择图片后的回调
          const tempFilePaths = res.tempFilePaths;
          // 使用uploadFile上传图片
          this.uploadPhoto(tempFilePaths[0]);
          uni.showToast({
              title: '图片传上成功了',
              icon: 'none'
          });
        },
        fail: (err) => {
          // 处理错误情况
          console.log('chooseImage fail', err);
          uni.showToast({
              title: '上传失败',
              icon: 'none'
          });
        }
      });


 // 上传图片到服务器
    uploadPhoto(photoPath) {
      // 显示加载中的提示
      uni.showLoading({
        title: '上传中...'
      });
      // 使用uniapp API上传文件
      uni.uploadFile({
        url: 'http://localhost:21371/api/Images/upload', // 服务器上传接口
        filePath: photoPath,
        name: 'file', // 必须填写,为了后端接收文件流的参数名字
        formData: {
          // 其他要上传的参数
          imageId:'123'
        },
        success: (uploadFileRes) => {
          // 上传成功的回调
          console.log('uploadFile success:', uploadFileRes);
          uni.hideLoading();
        
        },
        fail: (uploadFileErr) => {
          // 上传失败的回调
          console.log('uploadFile fail:', uploadFileErr);
          uni.hideLoading();
        
        }
      });
    },

4、后端上传代码

        [HttpPost("upload")]
       // public IActionResult UploadImage(IFormFile file)
             public string UploadImage([FromForm] LongModel.ITEMS model, IFormFile file)
        {

          
            // 保存图片到数据库
            byte[] imageData = null;
            using (var memoryStream = new MemoryStream())
            {
                file.CopyTo(memoryStream);
                imageData = memoryStream.ToArray();
            }
          
            // 插入图片数据到数据库
            using (var connection = new SqlConnection(sqlcon))
            {
                connection.Open();
                using (var command = new SqlCommand($"INSERT INTO Images (ImageData,imageId) VALUES (@ImageData,'{model.imageId}')", connection))
                {
                    command.Parameters.AddWithValue("@ImageData", imageData);
                    //command.Parameters.AddWithValue("@imageId", '1');
                    command.ExecuteNonQuery();
                }
            }

            return Utils.ResponseWrite("y", "yes", "数据处理成功"); //Ok("图片上传成功");//
        }

5、后端查询代码,请提供一个uniapp 查询图片代码

 [HttpGet("getImage/{imageId}")]
        public IActionResult GetImage(int imageId)
        {
            // 从数据库查询图片数据
            byte[] imageData = null;
            using (var connection = new SqlConnection(sqlcon))
            {
                connection.Open();
                using (var command = new SqlCommand("SELECT ImageData FROM Images WHERE ImageId = @ImageId", connection))
                {
                    command.Parameters.AddWithValue("@ImageId", imageId);
                    using (var reader = command.ExecuteReader())
                    {
                        if (reader.Read())
                        {
                            imageData = (byte[])reader["ImageData"];
                        }
                    }
                }
            }

            if (imageData == null)
            {
                return NotFound();
            }

            // 将图片数据转换为图片并返回
            return File(imageData, "image/jpeg");
        }

  • 写回答

25条回答 默认 最新

  • 专家-赤兔[在线] 优质创作者: 编程框架技术领域 2024-06-08 15:41
    关注
    获得0.30元问题酬金

    引自免费微信小程序:皆我百晓生

    看起来您在手机端遇到的问题可能是由于跨域访问控制或者是文件路径格式不正确导致的。针对这两个可能的问题,我将为您提供一些解决方案。

    首先,确保您的后端API允许来自移动设备的请求。在ASP.NET Core Web API中,您可以添加CORS(Cross-Origin Resource Sharing)中间件来解决这个问题。请按照以下步骤操作:

    1. Startup.cs文件的ConfigureServices方法中,添加CORS服务:
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddCors(options =>
        {
            options.AddPolicy("AllowAllOrigins",
                builder => builder.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader());
        });
    
        // ...其他服务配置...
    }
    

    这将允许所有源进行跨域访问。

    1. 确保在Configure方法中应用 CORS 中间件:
    public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
    {
        // ...
    
        app.UseRouting();
    
        app.UseCors("AllowAllOrigins");
    
        app.UseEndpoints(endpoints =>
        {
            endpoints.MapControllers();
        });
    
        // ...
    }
    

    接下来,对于前端部分,检查手机上的临时文件路径是否正确。在某些情况下,Android 和 iOS 的临时文件路径格式可能会有所不同。在调用 uni.chooseImage 后,确保您获取的是正确的文件路径格式。

    为了确保兼容性,您可以尝试使用getSavedFileList方法获取文件列表,然后根据文件类型过滤出图片文件。这里是一个示例:

    takePhoto() {
      uni.chooseImage({
        count: 1,
        sizeType: ['compressed'],
        sourceType: ['album']
      }).then(res => {
        uni.getSavedFileList({
          types: ['image'] // 获取图片文件
        }).then(fileList => {
          let tempFilePath = '';
          fileList.forEach(item => {
            if (item.type === 'image') {
              tempFilePath = item.path;
              break;
            }
          });
    
          if (!tempFilePath) {
            uni.showToast({ title: '未找到图片文件', icon: 'none' });
            return;
          }
    
          this.uploadPhoto(tempFilePath);
        });
      });
    },
    

    这样应该能解决手机端上传图片的问题。同时,为了完成后端的图片查询,您可以在uniapp中编写一个函数来调用GetImage API:

    async getImage(imageId) {
      try {
        const response = await uni.request({
          url: 'http://localhost:21371/api/Images/getImage/' + imageId,
          method: 'GET',
          responseType: 'arraybuffer' // 预期响应类型为ArrayBuffer,以便转换为图片
        });
    
        if (response.data) {
          // 将ArrayBuffer转换为Blob,然后创建URL
          const blob = new Blob([response.data], { type: 'image/jpeg' });
          const imageUrl = URL.createObjectURL(blob);
    
          // 使用图片URL显示图片
          return imageUrl;
        } else {
          uni.showToast({ title: '图片未找到', icon: 'none' });
        }
      } catch (error) {
        uni.showToast({ title: '获取图片失败', icon: 'none' });
      }
    }
    

    这个函数会异步地发送GET请求到指定的API,并尝试将响应的数据转换为图片URL。然后您可以将这个URL赋值给<img>元素的src属性来显示图片。

    以上就是对您所描述问题的解答,如果还有其他疑问,请随时提问。

    评论 编辑记录

报告相同问题?

问题事件

  • 系统已结题 6月16日
  • 创建了问题 6月8日