uniapp图片上传,加web core api接收并保存

Uni-App图片上传加后台web core Api

      • 前台代码
      • 后台Web Core Api代码
      • Startup.cs中代码

啥也不说了直接上代码!!!

前台代码

// An highlighted block
uni.chooseImage({
					count:1,
					success: (res) => {					
						uni.uploadFile({
							url:'http://localhost:24517/api/Upload/UpImgs',
							filePath:res.tempFilePaths[0],
							name:'image',//必填  此为类型名称
							formData:{
								'name':'Imgs'
							},
							header:{
								'token':'aaabbbcccddd'
							},
							success: (res) => {
								console.log(res);
							},
							fail:(err)=>{
								console.log(err);
							}
						})
					}
		})

后台Web Core Api代码

控制器中的代码


        [HttpPost]
        public IActionResult UpImgs([FromForm] IFormCollection formCollection)
        {
            WebResult web = new WebResult();
            //跟前端的控件名称保持一致
            var sn = Request.Form["name"];//formdata中的值
            var token = Request.Headers["token"];
            string user = token.ToString();
            FormFileCollection fileCollection = (FormFileCollection)formCollection.Files;
            foreach(IFormFile file in fileCollection)
            {
                StreamReader reader = new StreamReader(file.OpenReadStream());
                string content = reader.ReadToEnd();
                //string filepath = HostPath.HostEnv.ContentRootPath + "/UploadFile/Images/" + DateTime.Now.ToString("yyyyMM");//此处HostPath.HostEnv.ContentRootPath为获取项目的绝对路径
                string filepath = "D:/UploadFile/Images/" + DateTime.Now.ToString("yyyyMM");
                if (!System.IO.Directory.Exists(filepath))
                {
                    Directory.CreateDirectory(filepath);
                }
                string filename = DateTime.Now.ToString("yyyyMMddHHmmss")+"_"+file.FileName;
                using (FileStream fs = System.IO.File.Create(filepath + "/" + filename))
                {
                    file.CopyToAsync(fs);
                }
                web.data ="/UploadFile/Images/" + DateTime.Now.ToString("yyyyMM")+"/"+filename;
            }
            web.code = 0;
            web.msg = "成功";  
            return new JsonResult(web);
        }

你以为到这就结束了吗?
—看
—当然没有,因为还有跨域没有解决!!!

Startup.cs中代码

//注:这个方法在Startup中已存在,就添加一句services.AddCors就行
  public void ConfigureServices(IServiceCollection services)
  {
      services.AddCors(m => m.AddPolicy("any", a => a.AllowAnyOrigin().AllowAnyMethod().AllowAnyHeader())); 
      services.AddControllers();
  }

  //接下来在 Configure 中添加一个app.UseCors();
  public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
  {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseRouting();

            app.UseAuthorization();

            app.UseCors();

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
  }

最后,要在你的控制器顶部加一个引用

namespace MyWebApi.Controllers
{
   [EnableCors("any")]
   [Route("api/[controller]/[Action]")]
   public class UploadController : ControllerBase{
      ********此处都知道写啥吧,就是我上面的后台控制器代码*******
   }
}

你可能感兴趣的:(uni-app,javascript,c#,vue.js)