locked
MVC Web API Image upload and saving path in the database. RRS feed

  • Question

  • User271867911 posted

    I want to upload <g class="gr_ gr_179 gr-alert gr_gramm gr_inline_cards gr_run_anim Grammar only-ins doubleReplace replaceWithoutSep" id="179" data-gr-id="179">image</g> file and save the image path in the Products table in the database together with the other information like <g class="gr_ gr_170 gr-alert gr_gramm gr_inline_cards gr_run_anim Style multiReplace" id="170" data-gr-id="170"><g class="gr_ gr_163 gr-alert gr_spell gr_inline_cards gr_disable_anim_appear ContextualSpelling ins-del multiReplace" id="163" data-gr-id="163">poductName</g> ,</g> ProductDesc.

    I am not sure either <g class="gr_ gr_259 gr-alert gr_tiny gr_spell gr_inline_cards gr_run_anim ContextualSpelling multiReplace" id="259" data-gr-id="259">i</g> have to write one method or two methods for this. i.e one for image upload and one for saving data in the database.

    Can anyone suggest me how to do <g class="gr_ gr_365 gr-alert gr_gramm gr_inline_cards gr_run_anim Punctuation multiReplace" id="365" data-gr-id="365">it.</g>

    Wednesday, November 22, 2017 4:55 AM

All replies

  • User1572049755 posted

    Hello,

      As I know , I suggest you could upload your picture first, get the path of this picture on your server, than post all data and save them in the database. So, I mean, you may need 2 methods, one for upload picture and get the path of it , another one save the data.

    Wednesday, November 22, 2017 5:31 AM
  • User271867911 posted

    AnyCode reference?

    Wednesday, November 22, 2017 6:29 AM
  • User991499041 posted

    Hi Farooqspecials,

    AnyCode reference?

    Here is an article about how to upload files, save (insert) to database table, retrieve (display) files from database table and download the files from database table in ASP.Net MVC.

    The uploaded file is converted to an Array of Bytes using BinaryReader class and finally is inserted into the database table.

    If you want to save the picture path, you need to make some changes to the code.

    Regards,

    zxj

    Wednesday, November 22, 2017 7:51 AM
  • User1572049755 posted

    Hello,

    I can give you a reference, but you'd better change it in your way.

    <form id="form1" action="@Url.Action("SubmitData")" method="post" enctype="multipart/form-data">
            <div>
                <input id="image" name="poductImage" type="file" />          
            </div>
            <div>
                <input id="name" name="poductName" type="text" />       
            </div>
            <div>
                <input id="Button1" name="" type="submit" value="Submit" />
            </div>
        </form>
    
    
    
    [HttpPost]
            public ActionResult SubmitData()
            {
                string uppath = string.Empty;
                string savepath = string.Empty;
                try
                {
                    HttpPostedFileBase imgFile = Request.Files["poductImage"];
                    string productname = Request.Form["poductName"].ToString();
                    if (imgFile != null)
                    {
                        //create new name,also you can change on your way
                        string nameImg = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                        //get the image
                        string strPath = imgFile.FileName;
                        string type = strPath.Substring(strPath.LastIndexOf(".") + 1).ToLower();
                        if (ValidateImg(type))
                        {
                            //you can change the path
                            uppath = Server.MapPath("~/UpImgs/");
                            uppath += nameImg + "." + type;
                            //upload
                            imgFile.SaveAs(uppath);
                        }
    
                        //here you get the ProductName and Image
                        //you can save them in the DataBase
                        //So, you can only use one method
                        return View("your view");
                    }
                    //if no image
                    return View("upload fail");
                }
                catch (Exception e)
                {
                    //if any problem
                    return View("Something wrong");
                }
                
            }
    
            private bool ValidateImg(string imgName)
            {
                string[] imgType = new string[] { "gif", "jpg", "png", "bmp" };
    
                int i = 0;
                bool blean = false;
                string message = string.Empty;
    
                while (i < imgType.Length)
                {
                    if (imgName.Equals(imgType[i].ToString()))
                    {
                        blean = true;
                        break;
                    }
                    else if (i == (imgType.Length - 1))
                    {
                        break;
                    }
                    else
                    {
                        i++;
                    }
                }
                return blean;
            }

    Regards

    Wednesday, November 22, 2017 8:19 AM
  • User271867911 posted

    It is MVC .. .Not Web API

    Wednesday, November 22, 2017 1:15 PM
  • User-832373396 posted

    <g class="gr_ gr_87 gr-alert gr_gramm gr_inline_cards gr_run_anim Punctuation only-ins replaceWithoutSep" id="87" data-gr-id="87">Hi</g> <g class="gr_ gr_5 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling" id="5" data-gr-id="5">farooqspecia</g>,

    Sir, please refer to this working code to call web <g class="gr_ gr_66 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace" id="66" data-gr-id="66">api</g> for uploading <g class="gr_ gr_88 gr-alert gr_gramm gr_inline_cards gr_run_anim Grammar only-ins doubleReplace replaceWithoutSep" id="88" data-gr-id="88">image</g>:

    @{
        ViewBag.Title = "Part6";
    }
     
    <h2>Part6 - Upload file to web api using Http Client</h2>
    <div class="container">
        <div>
            @if (ViewBag.Success != null)
            {
                <div class="alert alert-success" role="alert">
                    <strong>Well done !</strong> Successfully uploaded. <a href="@ViewBag.Success" target="_blank">open file</a>
                </div>
            }
            else if(ViewBag.Failed != null)
            {
                <div class="alert alert-error" role="alert">
                    <strong>Error !</strong> @ViewBag.Failed
                </div>
            }
        </div>
        @using (Html.BeginForm("Part6","Home", FormMethod.Post,new{ role = "form", enctype="multipart/form-data"}))
        {
            <div class="form-group">
                <input type="file" id="file" name="file" />
            </div>
            <input type="submit" value="Submit" class="btn btn-default" />
        }
    </div>

    Then 

    namespace WebApiExample.Controllers
    {
        public class UploadController : ApiController
        {
            public Task<HttpResponseMessage> Post()
            {
                List<string> savedFilePath = new List<string>();
                if (!Request.Content.IsMimeMultipartContent())
                {
                    throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
                }
                string rootPath = HttpContext.Current.Server.MapPath("~/uploadFiles");
                var provider = new MultipartFileStreamProvider(rootPath);
                var task = Request.Content.ReadAsMultipartAsync(provider).
                    ContinueWith<HttpResponseMessage>(t =>
                    {
                        if (t.IsCanceled || t.IsFaulted)
                        {
                            Request.CreateErrorResponse(HttpStatusCode.InternalServerError, t.Exception);
                        }
                        foreach (MultipartFileData item in provider.FileData)
                        {
                            try
                            {
                                string name = item.Headers.ContentDisposition.FileName.Replace("\"", "");
                                string newFileName = Guid.NewGuid() + Path.GetExtension(name);
                                File.Move(item.LocalFileName, Path.Combine(rootPath, newFileName));
     
                                Uri baseuri = new Uri(Request.RequestUri.AbsoluteUri.Replace(Request.RequestUri.PathAndQuery, string.Empty));
                                string fileRelativePath = "~/uploadFiles/" + newFileName;
                                Uri fileFullPath = new Uri(baseuri, VirtualPathUtility.ToAbsolute(fileRelativePath));
                                savedFilePath.Add(fileFullPath.ToString());
                            }
                            catch (Exception ex)
                            {
                                string message = ex.Message;
                            }
                        }
     
                        return Request.CreateResponse(HttpStatusCode.Created, savedFilePath);
                    });
                return task;
            }
        }

    and call <g class="gr_ gr_238 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace" id="238" data-gr-id="238">api</g> and pass <g class="gr_ gr_282 gr-alert gr_gramm gr_inline_cards gr_run_anim Grammar only-ins doubleReplace replaceWithoutSep" id="282" data-gr-id="282">value</g>

     public ActionResult Part6()
            {
                return View();
            }
    
            [HttpPost]
            public ActionResult Part6(HttpPostedFileBase file)
            {
                using (var client = new HttpClient())
                {
                    using (var content = new MultipartFormDataContent())
                    {
                        byte[] Bytes = new byte[file.InputStream.Length + 1];
                        file.InputStream.Read(Bytes, 0, Bytes.Length);
                        var fileContent = new ByteArrayContent(Bytes);
                        fileContent.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment") { FileName = file.FileName };
                        content.Add(fileContent);
                        var requestUri = "http://localhost:1963/api/upload";
                        var result = client.PostAsync(requestUri, content).Result;
                        if (result.StatusCode == System.Net.HttpStatusCode.Created)
                        {
                            List<string> m = result.Content.ReadAsAsync<List<string>>().Result;
                            ViewBag.Success = m.FirstOrDefault();
    
                        }
                        else
                        {
                            ViewBag.Failed = "Failed !" + result.Content.ToString();
                        }
                    }
                }
                return View();
            }

    With regards, Angelina Jolie

    Friday, November 24, 2017 9:31 AM