I am uploading a file and wish to name it with one of the input fields which I wille be typing in my view. For ex: I type "Test" in my "Designation Commerciale" field. However, it gives me the NullReferenceException as it does not find any. Would appreciate your help. Thanks.
Controller:
public async Task<string> UploadFile(IFormFile file)
{
//bool iscopied;
string resp = String.Empty;
try
{
if (file.Length > 0)
{
var model = new IdentificationProduitViewModel();
string x = model.DesignationCommerciale;
string filename = x + Path.GetExtension(file.FileName);
string path = Path.GetFullPath(Path.Combine(Directory.GetCurrentDirectory(), "UploadFds"));
using (var filestream = new FileStream(Path.Combine(path, filename), FileMode.Create))
{
await file.CopyToAsync(filestream);
}
//iscopied = true;
resp = filename;
}
else
{
// iscopied = false;
resp = String.Empty;
}
}
catch(Exception)
{
throw;
}
return resp;
}
HTTPPOST:
string tryupload = await UploadFile(file_fds);
if (!String.IsNullOrEmpty(tryupload))
{
TempData["uploadok"] = "Fichier chargé avec success !";
model.Fds_Filepath = tryupload;
}
Related
Hello I Have a request in web form code behind and i like call web api send Object with a property of type IFormCollection, the object properties sending but file not
WebRequest wrqst = WebRequest.Create(URLService + method);
var postData = new StringBuilder();
foreach (string key in form.Keys)
{
postData.AppendFormat("{0}={1}&",
HttpUtility.UrlEncode(key),
HttpUtility.UrlEncode(form[key]));
}
var data = Encoding.ASCII.GetBytes(postData.ToString());
wrqst.Method = "POST";
wrqst.ContentType = "application/x-www-form-urlencoded";
wrqst.ContentLength = data.Length;
using (var stream = wrqst.GetRequestStream())
{
stream.Write(data, 0, data.Length);
}
WebResponse oResponse = wrqst.GetResponse();
I Receive file in Request.File
How i can send File?
To send a file in your web API request, you need to use the multipart/form-data content type instead of application/x-www-form-urlencoded.
[HttpPost]
[Route("api/WEB/Pos_PropertyImageSave")]
[Route("api/POS/Pos_PropertyImageSave")]
public HttpResponseMessage Pos_PropertyImageSave()
{
try
{
var request = HttpContext.Current.Request;
bool IsUpload= false;
/******************Image Upload*********************/
if (request.Files["PropertyImage"] != null )
{
obj.AttachemntName = request.Form["AttachemntName"] != null ? request.Form["AttachemntName"].ToString() : "";
obj.AttachemntNo = request.Form["AttachemntNo"] != null ? request.Form["AttachemntNo"].ToString() : "";
HttpPostedFile uploadImage = request.Files["PropertyImage"];
if (uploadImage.ContentLength > 0)
{
//Convert the File data to Byte Array which will be store in database
byte[] bytes;
using (BinaryReader br = new BinaryReader(uploadImage.InputStream))
{
bytes = br.ReadBytes(uploadImage.ContentLength);
}
filesInfo file = new filesInfo
{
File_Name = Path.GetFileName(uploadImage.FileName),
File_Type = uploadImage.ContentType,
File_Data = bytes
};
string FilePath = HttpContext.Current.Server.MapPath("~/Upload/") + Path.GetFileName(uploadImage.FileName);
File.WriteAllBytes(FilePath, bytes);
obj.AttachemntType = Path.GetExtension(uploadImage.FileName);
obj.AttachemntImagePath = "../Upload/" + Path.GetFileName(uploadImage.FileName); ;
obj.AttachemntImage = file.File_Data;
// obj.AttachemntName = Convert.ToBase64String(file.File_Data, 0, file.File_Data.Length);
}
IsUpload= true;
/*******************End Of Image Upload*************/
}
if (IsUpload)
{
String sMessage = string.Format("Image has been " + obj.Mode + " successufully.");
Response responseclass = new Response(sMessage, sMessage, ((int)HttpStatusCode.OK), true);
HttpResponseMessage response = Request.CreateResponse<Response>(HttpStatusCode.OK, responseclass);
return response;
}
else
{
Response responseclass = new Response("", "Image Upload Failed", ((int)HttpStatusCode.NoContent), true);
HttpResponseMessage response = Request.CreateResponse<Response>(HttpStatusCode.OK, responseclass);
return response;
}
}
catch (Exception ex)
{
FailureResponse responseclass1 = new FailureResponse(ex.Message.ToString(), ((int)HttpStatusCode.BadRequest), false);
HttpResponseMessage response1 = Request.CreateResponse<FailureResponse>(HttpStatusCode.OK, responseclass1);
throw new HttpResponseException(response1);
}
}
public class filesInfo
{
public string File_Name { get; set; }
public string File_Type { get; set; }
public byte[] File_Data { get; set; }
}
I'm returning a file as follows:
public async Task<IActionResult> GetFile(string id)
{
try
{
GetFileDataResponse retrieveResponse = new GetFileDataResponse();
retrieveResponse = GetFileData(Int32.Parse(id));
var folderName = Path.Combine("Resources", "Images");
var pathToSave = Path.Combine(Directory.GetCurrentDirectory(), folderName);
pathToSave = Path.Combine(pathToSave, retrieveResponse.FileUrl);
var fileName = Path.GetFileName(pathToSave);
var content = await System.IO.File.ReadAllBytesAsync(pathToSave);
new FileExtensionContentTypeProvider()
.TryGetContentType(fileName, out string contentType);
return File(content, contentType, fileName);
}
catch(Exception ex)
{
response.Success = false;
response.Message = ex.ToString();
return BadRequest() ;
}
}
Is there a way to send some data additional besides the file?
I want to send some data like "uploadedBy:1", but I don't know if this is possible, I read about some parameter in the content disposition but I'm not sure how to implement it.
Thanks in advance.
I am wrote the code to POST from my web application but it is sending 400 bad request.
See the my controller class:
[HttpPost]
public async Task<IActionResult> CreateAgent(AgentCreateDto agentCreateDto)
{
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("https://localhost:44331/api/");
var responseTask = client.PostAsJsonAsync("Agent/CreateAgent", agentCreateDto);
responseTask.Wait();
var result = responseTask.Result;
if (result.IsSuccessStatusCode)
{
var newAgentAdd = JsonConvert.DeserializeObject<AgentCreateDto>(await result.Content.ReadAsStringAsync());
var newAgent = newAgentAdd;
TempData["SuccessMessage"] = $"Agent {newAgent.FirstName} was successfully created.";
return RedirectToAction("AgentLists");
//return RedirectToAction("GetAgentById", new { AgentId = newAgent.usersId});
}
}
return View();
}
Here is below the problem image please see for the reference.
Here is api code for that I am send the request:
[HttpPost("CreateAgent")]
public async Task<IActionResult> CreateAgent([FromForm]AgentCreateDto agentCreateDto)
{
if (!ModelState.IsValid)
{
return BadRequest("Invalid model object");
}
if (agentCreateDto.ProfileImage != null)
{
string uniqueFileName = UploadProfileImage(agentCreateDto.ProfileImage);
agentCreateDto.ProfileNewImage = uniqueFileName;
}
var createAgent = await _userService.CreateAgent(agentCreateDto);
//_logger.LogInformation($"User added to the for file test. ");
return Created("", new
{
Id = createAgent.UsersId,
Message = "Agent created Successfully",
Status = "Success",
UserType = createAgent.UserType
});
}
And for image uploading code at the API side:
private string UploadProfileImage(IFormFile ProfileImage)
{
string uniqueFileName = null;
if (ProfileImage != null)
{
string uploadsFolder = Path.Combine(_webHostEnvironment.ContentRootPath, "ProfileImage");
uniqueFileName = Guid.NewGuid().ToString() + "_" + ProfileImage.FileName;
string filePath = Path.Combine(uploadsFolder, uniqueFileName);
using (var fileStream = new FileStream(filePath, FileMode.Create))
{
ProfileImage.CopyTo(fileStream);
}
}
return uniqueFileName;
}
The correct way to post file and additional data by HttpClient like below:
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("https://localhost:44331/api/");
var formContent = new MultipartFormDataContent();
formContent.Add(new StringContent(agentCreateDto.Id.ToString()), nameof(agentCreateDto.Id));
formContent.Add(new StringContent(agentCreateDto.Message), nameof(agentCreateDto.Message));
formContent.Add(new StringContent(agentCreateDto.UserType), nameof(agentCreateDto.UserType));
//other proerties....
formContent.Add(new StreamContent(agentCreateDto.ProfileImage.OpenReadStream()), nameof(agentCreateDto.ProfileImage), Path.GetFileName(agentCreateDto.ProfileImage.FileName));
//change PostAsJsonAsync to PostAsync.....
var responseTask = client.PostAsync("/Agent/CreateAgent", formContent);
responseTask.Wait();
var result = responseTask.Result;
//more code...
}
Net core application. I have one rest API which will send files to another API.
Below is the logic inside first API to send files to second API.
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", await _tokenService.GetToken());
MultipartFormDataContent multipartFormData = new MultipartFormDataContent();
string contentJson = JsonConvert.SerializeObject(request);
HttpContent data = new StringContent(contentJson, Encoding.UTF8, "application/json");
multipartFormData.Add(data, "data");
foreach (var file in fileList)
{
if (file.Length <= 0)
continue;
var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
multipartFormData.Add(new StreamContent(file.OpenReadStream())
{
Headers =
{
ContentLength = file.Length,
ContentType = new MediaTypeHeaderValue(file.ContentType)
}
}, "File", fileName);
}
try
{
var response = await client.PostAsync("https://localhost:44370/apisendfile", multipartFormData);
}
catch (Exception ex)
{
}
}
I have second API as below
public async Task<ActionResult> SendMail([FromBody] MultipartFormDataContent formDataContent)
{
}
When I debug in my first API I receive error
Unsupported Media Type
I am trying all the way to figure it out but could not succeed. Can someone help me to identify this issue. Any help would be appreciated. Thanks
Well, you could try following way,
Web API Controller:
[HttpPost]
public string UploadMultipartFile()
{
var file = HttpContext.Current.Request.Files.Count > 0 ?
HttpContext.Current.Request.Files[0] : null;
if (file != null && file.ContentLength > 0)
{
var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(
HttpContext.Current.Server.MapPath("~/MrPerfectMaltipartFolder"),
fileName
);
file.SaveAs(path);
}
return file != null ? "/MrPerfectMaltipartFolder/" + file.FileName : null;
}
Folder Location:
Tested on Post Man:
Open Folder Location:
File Uploaded:
For N Type of Multipart Data Upload:
[HttpPost]
public object UploadMultipartFileList()
{
var uploadedFilesName = new List<string>();
if (HttpContext.Current.Request.Files.Count > 0)
{
int count = 0;
foreach (var item in HttpContext.Current.Request.Files)
{
var getFile = HttpContext.Current.Request.Files[count];
if (getFile != null)
{
var fileName = Path.GetFileName(getFile.FileName);
var path = Path.Combine(
HttpContext.Current.Server.MapPath("~/MrPerfectMaltipartFolder"),
fileName
);
getFile.SaveAs(path);
}
count++;
string file = "/MrPerfectMaltipartFolder/" + getFile.FileName;
uploadedFilesName.Add(file);
}
}
return uploadedFilesName;
}
Output:
Example Both Data and File:
[HttpPost]
public object UploadMultipartFileList()
{
HttpRequest multipartRquest = HttpContext.Current.Request;
//General Data Part
string engineerName = multipartRquest.Form["EngineerName"];
string engineerEmail = multipartRquest.Form["EngineerEmail"];
//File Upload Part
var FilesName = new List<string>();
if (HttpContext.Current.Request.Files.Count > 0)
{
int count = 0;
foreach (var item in HttpContext.Current.Request.Files)
{
var getFile = HttpContext.Current.Request.Files[count];
if (getFile != null)
{
var fileName = Path.GetFileName(getFile.FileName);
var path = Path.Combine(
HttpContext.Current.Server.MapPath("~/MrPerfectMaltipartFolder"),
fileName
);
getFile.SaveAs(path);
}
count++;
string file = "/MrPerfectMaltipartFolder/" + getFile.FileName;
FilesName.Add(file);
}
}
return FilesName;
}
Request Format:
Output:
Hope it would resolve your problem. Feel free to share if you still encounter any issues.
Correct API style :
[HttpPost("logfiles")] // etc
public async Task<IActionResult> AddLogFile(IFormFile reportFile)
{
//UploadFile with any options with correct property Name = "ReportFile"
// all assigment will do framework itself in default impl
if (reportFile == null || reportFile.Length <= 0)
{
Submit client side style :
using (MultipartFormDataContent httpContent = new MultipartFormDataContent())
{
// read bytes from memstream etc
//...
httpContent.Add((HttpContent) bytes, "ReportFile", "test.log");
I'm uploading a image using Web API.
public IHttpActionResult UploadImage()
{
FileDescription filedescription = null;
var allowedExt=new string[]{".png",".jpg",".jpeg"};
var result = new HttpResponseMessage(HttpStatusCode.OK);
if (Request.Content.IsMimeMultipartContent())
{
Request.Content.LoadIntoBufferAsync().Wait();
var imgTask = Request.Content.ReadAsMultipartAsync<MultipartMemoryStreamProvider>(new MultipartMemoryStreamProvider()).ContinueWith((task) =>
{
MultipartMemoryStreamProvider provider = task.Result;
var content = provider.Contents.ElementAt(0);
Stream stream = content.ReadAsStreamAsync().Result;
Image image = Image.FromStream(stream);
var receivedFileName = content.Headers.ContentDisposition.FileName.Replace("\"", string.Empty);
var getExtension = Path.GetExtension(receivedFileName);
if(allowedExt.Contains(getExtension.ToLower())){
string newFileName = "TheButler" + DateTime.Now.Ticks.ToString() + getExtension;
var originalPath = Path.Combine("Folder Path Here", newFileName);
image.Save(originalPath);
var picture = new Images
{
ImagePath = newFileName
};
repos.ImagesRepo.Insert(picture);
repos.SaveChanges();
filedescription = new FileDescription(imagePath + newFileName, picture.Identifier);
}
});
if (filedescription == null)
{
return ResponseMessage(Request.CreateResponse(HttpStatusCode.InternalServerError, new { message="some error msg."}));
}
else
{
return ResponseMessage(Request.CreateResponse(HttpStatusCode.OK, filedescription));
}
}
else
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotAcceptable, new { message = "This request is not properly formatted" }));
}
}
Above code I have used to save image, But every time filedescription even after image is successfully saved. What's wrong I'm doing here.
I want to return filedescription after image save.
You are using a lot of async methods in the wrong way. You should never make a call to an async method and then wait for it to finish in a synchronous manner (e.g. using Wait() or Result).
If an API exposes an async method, then await for it, turning also the calling method into an async method.
The reason why your filedescription variable is always null, is because you are checking it before you continuation has finished. This is truly a bad practice: if you need a value that is a result of an async operation, then you have to wait for it to finish, but in this case, using the await keyword.
This is the correct way of calling async methods and wait (asynchronously) for them to finish:
public async Task<IHttpActionResult> UploadImage()
{
FileDescription filedescription = null;
var allowedExt = new string[] { ".png", ".jpg", ".jpeg" };
var result = new HttpResponseMessage(HttpStatusCode.OK);
if (Request.Content.IsMimeMultipartContent())
{
await Request.Content.LoadIntoBufferAsync();
var provider = await Request.Content.ReadAsMultipartAsync(new MultipartMemoryStreamProvider());
var content = provider.Contents.ElementAt(0);
Stream stream = await content.ReadAsStreamAsync();
Image image = Image.FromStream(stream);
var receivedFileName = content.Headers.ContentDisposition.FileName.Replace("\"", string.Empty);
var getExtension = Path.GetExtension(receivedFileName);
if (allowedExt.Contains(getExtension.ToLower()))
{
string newFileName = "TheButler" + DateTime.Now.Ticks.ToString() + getExtension;
var originalPath = Path.Combine("Folder Path Here", newFileName);
image.Save(originalPath);
var picture = new Images
{
ImagePath = newFileName
};
repos.ImagesRepo.Insert(picture);
repos.SaveChanges();
filedescription = new FileDescription(imagePath + newFileName, picture.Identifier);
}
if (filedescription == null)
{
return ResponseMessage(Request.CreateResponse(HttpStatusCode.InternalServerError, new { message = "some error msg." }));
}
else
{
return ResponseMessage(Request.CreateResponse(HttpStatusCode.OK, filedescription));
}
}
else
{
throw new HttpResponseException(Request.CreateResponse(HttpStatusCode.NotAcceptable, new { message = "This request is not properly formatted" }));
}
}