ASP.NET MVC3: Image loading through controller - image

I tried using the answer from here, but it did not work. I have the following code:
public ActionResult ShowImage()
{
using (FileStream stream = new FileStream(Path.Combine(Server.MapPath("/App_Data/UserUpload/asd.png")), FileMode.Open))
{
FileStreamResult result = new FileStreamResult(stream, "image/png");
result.FileDownloadName = "asd.png";
return result;
}
}
When I open up the page I get an error which says: "Cannot access a closed file.". I did some googling on the error, but I only found this error associated with uploading. What causes the issue here?

Try like this:
public ActionResult ShowImage()
{
var file = Server.MapPath("~/App_Data/UserUpload/asd.png");
return File(file, "image/png", Path.GetFileName(file));
}
or if you want a separate filename:
public ActionResult ShowImage()
{
var path = Server.MapPath("~/App_Data/UserUpload");
var file = "asd.png";
var fullPath = Path.Combine(path, file);
return File(fullPath, "image/png", file);
}

Related

How to pass file in Wep API in asp.net core 2.2

I want to pass file in web api
Controller:
[HttpPost]
public IActionResult Upload(IFormFile file)
{
string d = file.FileName;
//string contents = JsonConvert.SerializeObject(d);
using (HttpResponseMessage response = objAPI.CallAPIGet("/BusinessProfile/saveFolder", d))
{
if (response.IsSuccessStatusCode)
{
string responseString = response.Content.ReadAsStringAsync().Result;
if (!string.IsNullOrEmpty(responseString))
{
}
}
}
return Ok();
}
Web Api:
[HttpPost]
[Route("saveFolder")]
public IActionResult WriteFile(IFormFile file)
{
string fileName;
try
{
var extension = "." + file.FileName.Split('.')[file.FileName.Split('.').Length - 1];
//fileName = Guid.NewGuid().ToString() + extension; //Create a new Name
fileName = file.FileName;
var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot\\BProfileFile", fileName);
using (var bits = new FileStream(path, FileMode.Create))
{
file.CopyToAsync(bits);
}
}
catch (Exception ex)
{
throw ex;
}
return Ok(fileName);
}
from UI to web api method is not heat. the error is
Unsupported Media Type.
How to solve this error.

How to upload picture in Spring and Angular2

I want to upload picture in my app this is my Angular 2 code
constructor () {
this.progress = Observable.create(observer => {
this.progressObserver = observer
}).share();
}
public makeFileRequest (url: string, params: string[], files: File[]):
Observable<any> {
return Observable.create(observer => {
let formData: FormData = new FormData(),
xhr: XMLHttpRequest = new XMLHttpRequest();
for (let i = 0; i < files.length; i++) {
formData.append("uploads[]", files[i], files[i].name);
}
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
observer.next(JSON.parse(xhr.response));
observer.complete();
} else {
observer.error(xhr.response);
}
}
};
xhr.upload.onprogress = (event) => {
this.progress = Math.round(event.loaded / event.total * 100);
this.progressObserver.next(this.progress);
};
xhr.open('POST', url, true);
xhr.send(formData);
});
}
And this is my spring controller
#RequestMapping(value = "/upload", method = RequestMethod.POST)
#ResponseBody
public ResponseEntity<?> uploadFile(
#RequestParam("file") MultipartFile uploadfile) {
try {
// Get the filename and build the local file path (be sure that the
// application have write permissions on such directory)
String filename = uploadfile.getOriginalFilename();
String directory = "/assets/images";
String filepath = Paths.get(directory, filename).toString();
// Save the file locally
BufferedOutputStream stream =
new BufferedOutputStream(new FileOutputStream(new File(filepath)));
stream.write(uploadfile.getBytes());
stream.close();
}
catch (Exception e) {
System.out.println(e.getMessage());
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
return new ResponseEntity<>(HttpStatus.OK);
}
And I get this error
ERROR {"timestamp":1498220487868,"status":400,"error":"Bad Request","exception":"org.springframework.web.multipart.support.MissingServletRequestPartException","message":"Required request part 'file' is not present","path":"/webapp/api/picture/upload"}
You specify #RequestParam("file"), which means Spring waits for an argument with the key file, but you append your data with the key uploads.
Also, as said by #ledniov, your are receiving an array of multipart files, not only one.
Corrections if you want to use the key file:
// Front-End: change "uploads" to "file"
formData.append("file[]", files[i], files[i].name);
// Back-End: takes a MultipartFile array
#RequestParam("file") MultipartFile[] uploadfile
Corrections if you want to use the key uploads:
// Back-End: change "file" to "uploads" and takes a MultipartFile array
#RequestParam("uploads") MultipartFile[] uploadfile

Make IFormFile function to work with model

I have a function in my controller that takes a file sent by an ajax call and saves it to a specified path. I was wondering how I could make this work with a model instead as I am hoping to send more data than just the image.
ViewModel:
public class PhotoViewModel
{
// Other strings
public IFormFile userimage { get; set; }
}
Controller: Without model (working)
[HttpPost]
public async Task<IActionResult> Post(IFormFile file)
{
var filePath = Path.GetFullPath(#"C:\Users\me\documents\" + file.FileName);
if (file.Length > 0)
{
using (var stream = new FileStream(filePath, FileMode.Create))
{
await file.CopyToAsync(stream);
}
}
return StatusCode(200);
}
Attempt at Version with Model:
[HttpPost]
public async Task<IActionResult> PhotoData(PhotoViewModel model)
{
var filePath = Path.GetFullPath(#"C:\Users\me\documents\" + model.userimage.FileName);
if (ModelState.IsValid)
{
if (model.userimage.Length > 0)
{
using (var stream = new FileStream(filePath, FileMode.Create))
{
await model.userimage.CopyToAsync(stream);
}
}
}
return StatusCode(200);
}
This attempt doesn't get me far. By setting a breakpoint I can see it fails at setting the filePath but I'm not sure how to work with the model. Any help is appreciated.
What is the error message you are getting and what is the client side code you are using to send the API request?
You will have to use a FormData object and fill the FormData object with the required properties.
var formData = new FormData();
formData.append(add PhotoViewModel properties)
formData.append(userimage, <file>);

IN MVC6 return Json(rows, JsonRequestBehavior.AllowGet) ISSUE

IN MVC6 return Json(rows, JsonRequestBehavior.AllowGet); method is changed and not allowing to set JsonrequestBehavior. What is alternative in MVC6
That overload of Json method which takes JsonRequestBehavior does not exist in the aspnet core any more.
You can simply call the Json method with the object data you want to send back.
public IActionResult GetJsonData()
{
var rows = new List<string> { "Item 1","Item 2" };
return Json(rows);
}
Or even
public IList<string> GetJsonData()
{
var rows = new List<string> {"aa", "bb" };
return rows;
}
or using Ok method and having IActionResult as the return type.
public IActionResult GetJsonData()
{
var rows = new List<string> { "aa", "bb" };
return Ok(rows);
}
and let the content negotiator return the data in the requested format(via Accept header). The default format used by ASP.NET Core MVC is JSON. So if you are not explicitly requesting another format(ex :application/xml), you will get json response.
Try this
[HttpGet]
public JsonResult List()
{
var settings = new JsonSerializerSettings();
return Json(rows, settings);
}
Try this
public JsonResult GetJsonData()
{
var data= //your list values
return Json(data);
}
JsonRequestBehavior is deprecated from ASP.net core 1. Just use return Json();

Hide image using Javascript after controller action is complete MVC3

My application has been implemeted using MVC 3, .net.
I am trying to generate an excel file at the click of a button.
The call to the controller action is made using Ajax.
My main problem is: During the file generation i am trying to display an image on the screen to let the user know of the ingoing operation. I can very well display the image but i cannot hide it after the operation is completed. The codei am using is :
Javascript code:
$("input.DownloadExcelReport").click(function (e) {
e.preventDefault();
var parameter = -- code to fetch parameter value;
var outputViewUrl = (the url is created here);
showLoading(); -- This function displays the image
window.location.href = outputViewUrl;
});
Controller Action code:
public ActionResult DownExcelReportForAssortment(Guid parameter)
{
try
{
//the contents for the file generation are fetched here..
// Write contents to excel file
if (memoryStream != null)
{
var documentName = "Report.xls";
byte[] byteArrary = memoryStream.ToArray();
return File(byteArrary, "application/vnd.ms-excel", documentName);
}
}
catch (Exception ex)
{
LogManager.LogException(ex);
}
}
I do not return a Json result to the calling javascript method where i can write the code to hide the image.
I am returning a file which can be saved by the user and the action is completed.
Can somone please suggect/help me of how can i hide the image once the file generation operation is complete?
Appreciate the help...
You may checkout the following article and put this into action. So we start by defining a controller:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult DownExcelReportForAssortment(Guid parameter, string tokenId)
{
// Simulate some heavy work to fetch the report
Thread.Sleep(5000);
// we fake it
byte[] byteArray = System.IO.File.ReadAllBytes(#"c:\test.xls");
var cookie = new HttpCookie("fileDownloadToken", tokenId);
Response.AppendCookie(cookie);
return File(byteArray, "application/vnd.ms-excel", "report.xls");
}
}
and in the view:
#Html.ActionLink(
"download report",
"DownExcelReportForAssortment",
"Home",
new { parameter = Guid.NewGuid(), tokenId = "__token__" },
new { #class = "download" }
)
Now the last step is to include the jquery.cookie plugin:
<script type="text/javascript" src="#Url.Content("~/scripts/jquery.cookie.js")"></script>
and write a script to subscribe to the click event of the anchor and track the download progress:
$(function () {
var fileDownloadCheckTimer;
$('.download').click(function () {
var token = new Date().getTime();
$(this).attr('href', function () {
return this.href.replace('__token__', token);
});
// Show the download spinner
$('body').append('<span id="progress">Downloading ...</span>');
// Start polling for the cookie
fileDownloadCheckTimer = window.setInterval(function () {
var cookieValue = $.cookie('fileDownloadToken');
if (cookieValue == token) {
window.clearInterval(fileDownloadCheckTimer);
$.cookie('fileDownloadToken', null);
// Hide the download spinner
$('#progress').remove();
}
}, 1000);
});
});

Resources