コード例 #1
0
ファイル: PhotoController.cs プロジェクト: alishakkouf/yamama
        public async Task <IActionResult> addphoto(ImageViewModel model)
        {
            try
            {
                //check if the sent model not null
                if (ModelState.IsValid)
                {
                    // declare a variable
                    string fileName = null;

                    //check if the sent model has a photo
                    if (model.photo != null)
                    {
                        //declare a variable and stor in it the path of the uploaded files and photos
                        string uploading = Path.Combine(_env.WebRootPath, "Upload");

                        //give the uploaded file a unique name

                        fileName = Guid.NewGuid().ToString() + "_" + model.photo.FileName;

                        // declare a variable and store in it the name of file and the path
                        string filePath = Path.Combine(uploading, fileName);

                        model.photo.CopyTo(new FileStream(filePath, FileMode.Create));
                    }
                    //create a new object from photo class
                    Photo newphoto = new Photo
                    {
                        Path      = fileName,
                        ProjectId = model.ProjectId,
                        //Name = model.Name,
                    };

                    // add the new photo object to the database
                    await _photo.AddPhotoAsync(newphoto);

                    //save the changes
                    await _db.SaveChangesAsync();

                    var Response = new ResponseViewModel(true, HttpStatusCode.OK, "SUCCESS", newphoto);
                    return(Ok(Response));
                }

                return(null);
            }

            catch (Exception)
            {
                var Response = new ResponseViewModel(false, HttpStatusCode.NoContent, "failed", null);
                return(Ok(Response));
            }
        }