Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- [ValidateAntiForgeryToken]
- [HttpPost]
- public ActionResult Add(Mobile newM, HttpPostedFileBase image)
- {
- string filepath = "", filename = "", fileext = "", savepath = "";
- if (ModelState.IsValid)
- {
- if (image != null)
- {
- filepath = image.FileName;
- filename = newM.ID + "_" + Path.GetFileName(filepath);
- fileext = Path.GetExtension(filename);
- savepath = Server.MapPath("~/Images/" + filename);
- if (CheckExt(fileext))
- {
- newM.Image = filename;
- //image.SaveAs(savepath);
- }
- else
- {
- ModelState.AddModelError("", "Only allow: png, jpg, jpeg, gif");
- return View();
- }
- }
- var result = client.PostAsJsonAsync(baseURI, newM).Result;
- if (result.IsSuccessStatusCode)
- {
- if (image != null)
- {
- image.SaveAs(savepath);
- // Upload through API
- var content = new MultipartFormDataContent();
- var fileContent = new StreamContent(image.InputStream);
- fileContent.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("form-data")
- {
- Name = "UploadedFile",
- FileName = "\"" + filename + "\""
- };
- fileContent.Headers.ContentType = new MediaTypeHeaderValue(image.ContentType);
- content.Add(fileContent);
- client.PostAsync(baseURI + "upload", content);
- }
- return RedirectToAction("Index");
- }
- ModelState.AddModelError("", result.StatusCode.ToString());
- }
- return View();
- }
- //-------------------------------------API----------------------------------
- [HttpGet]
- [Route("api/mobileapi/image/{id}")]
- public IHttpActionResult image(int id)
- {
- string path = System.Web.Hosting.HostingEnvironment.MapPath("~/Images/" + GetMobile(id).Image);
- var file = File.OpenRead(path);
- var response = new HttpResponseMessage(HttpStatusCode.OK);
- response.Content = new StreamContent(file);
- //response.Content.Headers.ContentType = new MediaTypeHeaderValue("image/jpg");
- response.Content.Headers.ContentLength = file.Length;
- return ResponseMessage(response);
- }
- [Route("api/mobileapi/upload")]
- [HttpPost]
- public async Task<IHttpActionResult> upload()
- {
- var provider = new MultipartMemoryStreamProvider();
- await Request.Content.ReadAsMultipartAsync(provider);
- foreach (var file in provider.Contents)
- {
- var filename = file.Headers.ContentDisposition.FileName.Trim('\"');
- var buffer = await file.ReadAsByteArrayAsync();
- var filePath = System.Web.Hosting.HostingEnvironment.MapPath("~/Images/" + filename);
- File.WriteAllBytes(filePath, buffer);
- }
- return Ok();
- }
- [Route("api/mobileapi/delete/{id}")]
- [HttpPost]
- public IHttpActionResult delete(int id)
- {
- string path = System.Web.Hosting.HostingEnvironment.MapPath("~/Images/" + GetMobile(id).Image);
- File.Delete(path);
- return Ok();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement