Download a file with AngularJS + FileSaver.js + .Net MVC - angularjs

I'm trying to download an file what can be pdf, cvs, word, jpg or png. To do this, I'm using angularjs + filesaver.js. don't know why but, my downloads are always corrupted.
Someone can help me ?
Note:
midia.Nome - Name of my file.
midia.Tipo - The type of the file.
midia.Path - Physical path on project.
midia.MidiaBytesString - Bytes
on Base64 to convert to blob.
Download <br />
My File download method:
$scope.Download = function(bytes,nome,tipo){
var file = new File([bytes], nome , {type: "application/octet-stream"});
saveAs(file);
};
My View Model
public class MidiaViewModel
{
public int MidiaId { get; set; }
public string MidiaDescricao { get; set; }
//public string MidiaPath { get; set; }
public byte[] MidiaBytes { get; set; }
public string MidiaBytesString { get; set; }
public int OsId { get; set; }
public virtual OsViewModel Os { get; set; }
public string MidiaNome { get; set; }
public string MidiaType { get; set; }
public string MidiaPath { get; set; }
public long MidiaSize { get; set; }
}
My register Midia:
[HttpPost]
public JsonResult AtualizarMidias(IEnumerable<HttpPostedFileBase> arquivos, IEnumerable<string> descricoes, int osId)
{
var ordermDeServico = _osService.ObterPorIdLazyLoad(osId);
foreach (var file in arquivos)
{
string targetFolder = HttpContext.Server.MapPath("~/Content/uploads/");
string targetPath = Path.Combine(targetFolder, file.FileName);
if (file != null && file.ContentLength > 0)
{
var itens = arquivos.ToList();
var des = descricoes.ToList();
var index = itens.FindIndex(c => c.FileName == file.FileName);
var midiaViewModel = new MidiaViewModel
{
MidiaType = file.ContentType,
MidiaNome = file.FileName,
MidiaPath = targetPath,
MidiaSize = file.ContentLength,
MidiaDescricao = des[index].ToString(),
MidiaBytes = converterArquivo(file)
};
var midia = Mapper.Map<MidiaViewModel, Midia>(midiaViewModel);
midia.OsId = ordermDeServico.OSId;
file.SaveAs(targetPath);
_midiaService.Salvar(midia);
}
}
return Json(new { resultado = true }, JsonRequestBehavior.AllowGet);
}
And where i make the call to my angular $scope:
[HttpPost]
public string getMidiasOS(int idOS)
{
var getMidias = _midiaService.ObterMidiaPorIdOs(idOS);
List<MidiaAngularViewModel> midiaNova = new List<MidiaAngularViewModel>();
foreach (var midia in getMidias)
{
midiaNova.Add(new MidiaAngularViewModel
{
Id = midia.MidiaId,
Path = midia.MidiaPath,
Tipo = midia.MidiaType,
Descricao = midia.MidiaDescricao,
MidiaBytesString = Convert.ToBase64String(midia.MidiaBytes),
Nome = midia.MidiaNome
});
}
return JsonConvert.SerializeObject(midiaNova);
}
EDIT
Guys, I solved my problem using the Ameni topic in the follow link: download file using angularJS and asp.net mvc
All I need to do was create like the Post method on the Ameni topic and the download by path function.

Simply add/use the download attribute and you will be fine. More about download attribute can be found at w3c download documentation.
Download

Related

How to fix the error when only some data is displayed using web API on Xamarin Android

I created a personal info page to display all the data according to specific username entered. Unfortunately, the edit text didn't display all the data from the SQL Server. It only shows 2/8 data. I'm using a WEB API to retrieve the data and the data is stored in SQL Server. Can you help me to fix this problem please!!
I obtained this code from a website and i follow step by step according to the website. I've tried using Web services, it didn't work ass well.
VehicleRecord.cs
public class VehicleRecord
{
public string clFullName{ get; set; }
public string clGender{ get; set; }
public string clICNo { get; set; }
public string clAddress { get; set; }
public string clPhoneNo { get; set; }
public string clEmail { get; set; }
public string clUsername { get; set; }
public string clPwd { get; set; }
public string clVehicPlateNo { get; set; }
public string clVehicModel { get; set; }
public string clVehicCol { get; set; }
public string clPaymentMethod { get; set; }
public VehicleRecord()
{
this.clFullName = "";
this.clGender = "";
this.clICNo = "";
this.clAddress = "";
this.clPhoneNo = "";
this.clEmail = "";
this.clUsername = "";
this.clPwd = "";
this.clVehicPlateNo = "";
this.clVehicModel = "";
this.clVehicCol = "";
this.clPaymentMethod = "";
}
}
Service.cs
public class Service
{
public static async Task<dynamic> getServiceData(string queryString)
{
dynamic acc = null;
HttpClient client = new HttpClient();
var response = await client.GetAsync(queryString);
if(response != null)
{
string json = response.Content.ReadAsStringAsync().Result;
acc = JsonConvert.DeserializeObject(json);
}
return acc;
}
}
Acc.cs
public class Acc
{
public static async Task<VehicleRecord> GetAcc(string username)
{
string queryString = "http://xxx.xxx.x.xxx/PMSAPI1/api/users/" + username;
dynamic results = await Service.getServiceData(queryString).ConfigureAwait(false);
if(results != null)
{
VehicleRecord vehicleRecord = new VehicleRecord();
vehicleRecord.clFullName = (string)results["clFullName"];
vehicleRecord.clGender = (string)results["clGender"];
vehicleRecord.clICNo = (string)results["clICNo"];
vehicleRecord.clAddress = (string)results["clAddress"];
vehicleRecord.clPhoneNo = (string)results["clPhoneNo"];
vehicleRecord.clEmail = (string)results["clEmail"];
vehicleRecord.clPwd = (string)results["clPwd"];
vehicleRecord.clVehicPlateNo = (string)results["clVehicPlateNo"];
vehicleRecord.clVehicModel = (string)results["clVehicModel"];
vehicleRecord.clVehicCol = (string)results["clVehicCol"];
vehicleRecord.clPaymentMethod = (string)results["clPaymentMethod"];
return vehicleRecord;
}
else
{
return null;
}
}
}
PersonalInfoActivity.cs
private async void BtnGetAcc_Click(object sender, EventArgs e)
{
EditText username = FindViewById<EditText>(Resource.Id.txtUsername);
if (!String.IsNullOrEmpty(username.Text))
{
VehicleRecord vehicleRecord = await Acc.GetAcc(username.Text);
FindViewById<EditText>(Resource.Id.txtFullName).Text = vehicleRecord.clFullName;
FindViewById<EditText>(Resource.Id.txtGender).Text = vehicleRecord.clGender;
FindViewById<EditText>(Resource.Id.txtIC).Text = vehicleRecord.clICNo;
FindViewById<EditText>(Resource.Id.txtAddress).Text = vehicleRecord.clAddress;
FindViewById<EditText>(Resource.Id.txtPhoneNo).Text = vehicleRecord.clPhoneNo;
FindViewById<EditText>(Resource.Id.txtEmail).Text = vehicleRecord.clEmail;
FindViewById<EditText>(Resource.Id.txtPwd).Text = vehicleRecord.clPwd;
FindViewById<EditText>(Resource.Id.txtPayMethod).Text = vehicleRecord.clPaymentMethod;
}
}
The expected output should display all the data according to the username entered, but the actual output only displayed 2/8 data.
The error that i get is System.NullReferenceException:Object reference not set to an instance of an object.
The output displayed on screen
It seems to me that the issue starts at this line
vehicleRecord.clICNo = (string)results["clICNo"];
IMO results does not contains "clICNo". Check this by surrounding this line in try - catch block.

Upload pdf or doc into database of ASP.NET MVC-5 application

Hi,
I have been learning ASP.NET as well as doing a small project through MVC application.
My application is based on raising a purchase request for a product by an institution. It's a basic form through which all data are stored in DB.
How to add upload PDF or DOC into this coding so that the pdf quotation can be uploaded while submitting the form.
**
My Model
**
namespace sparki02.Models{
public class PRview
{
public int Id { get; set; }
[DataType(DataType.Html)]
public string Caption { get; set; }
[Required]
[DataType(DataType.ImageUrl)]
public string ImageUrl { get; set; }
[Required]
[StringLength(100)]
[Display(Name = "Supplier Name")]
public string SupplierName { get; set; }
[Required]
[StringLength(255)]
[Display(Name = "Material Name")]
public string MATName { get; set; }
[Required]
[StringLength(100)]
public string Brand { get; set; }
public PRtype PRtype { get; set; }
[Display(Name = "PR Type")]
public byte PRtypeId { get; set; }
[Required]
[Display(Name = "Unit Price")]
public double Unitprice { get; set; }}}
**
2. Controller
**
public ActionResult NewPR()
{var prtypes = _context.PRtypes.ToList();
var viewModel = new NewPRViewModel
{PRview = new PRview(),
PRtypes = prtypes};
return View("NewPR", viewModel);
}
[HttpPost]
public ActionResult Save(PRview prview, NewPRViewModel model)
{
var validImageTypes = new string[]
{
"image/gif",
"image/jpeg",
"image/pjpeg",
"image/png"
};
if (model.ImageUpload == null || model.ImageUpload.ContentLength == 0)
{
ModelState.AddModelError("ImageUpload", "This field is required");
}
else if (validImageTypes.Contains(model.ImageUpload.ContentType))
{
ModelState.AddModelError("ImageUpload", "Please choose either a GIF, JPG or PNG image.");
}
if (!ModelState.IsValid)
{
var viewModel = new NewPRViewModel
{
PRview = prview,
PRtypes = _context.PRtypes.ToList(),
Caption = model.Caption
};
return View("NewPR", viewModel);
}
if (prview.Id == 0)
_context.PRviews.Add(prview);
else
{
var prviewInDb = _context.PRviews.Single(c => c.Id == prview.Id);
prviewInDb.PRtypeId = prview.PRtypeId;
prviewInDb.MATName = prview.MATName;
prviewInDb.SupplierName = prview.SupplierName;
prviewInDb.Brand = prview.Brand;
prviewInDb.Unitprice = prview.Unitprice;
prviewInDb.ImageUrl = prview.ImageUrl;
if (model.ImageUpload != null && model.ImageUpload.ContentLength > 0)
{
var uploadDir = "~/uploads";
var imagePath = Path.Combine(Server.MapPath(uploadDir), model.ImageUpload.FileName);
var imageUrl = Path.Combine(uploadDir, model.ImageUpload.FileName);
model.ImageUpload.SaveAs(imagePath);
prview.ImageUrl = imageUrl;
}
}
_context.SaveChanges();
return RedirectToAction("Index", "PRview");
**
My View block
** Only content related to file upload
{ #model sparki02.ViewModels.NewPRViewModel
#using (Html.BeginForm("Save", "PRview", FormMethod.Post, new { enctype = "multipart/form-data" }))
{#Html.ValidationSummary(true, "Please fix the following errors.")
<div>
#Html.LabelFor(m => m.Caption)
#Html.EditorFor(m => m.Caption)
</div>
<div>
#Html.LabelFor(m => m.ImageUpload)
#Html.TextBoxFor(m => m.ImageUpload, new { type = "file" })
</div>
<button type="submit">Create</button>
<div class="form-group">
<button type="submit" class="btn btn-primary">Save</button>
</div>
<div class="form-group"> <p> #DateTime.Now</p> </div>
}
Whereas it is non-trivial to Download or View PDFs, it is relatively trivial to upload them. I used https://learn.microsoft.com/en-us/aspnet/core/mvc/models/file-uploads?view=aspnetcore-2.2 as mentioned by ADyson, but only about 5% of the code is really necessary.
In your CSHTML, you must add a Form File:
<input type="file" class="custom-control-input" tabindex="0" asp-for="FileUpload.FormFile">
<label asp-for="FileUpload.FormFile" class="custom-control-label">Upload Form</label>
Your form must include
enctype="multipart/form-data"
Your class must include:
[Required]
[BindProperty]
public BufferedSingleFileUploadDb FileUpload { get; set; }
}
public class BufferedSingleFileUploadDb
{
[Required]
[Display(Name = "File")]
public IFormFile FormFile { get; set; }
}
And in your Controller, here's some code that will work, although I commented out Microsoft's AppFile suggestion. You can save the file to a filesystem, database, etc.:
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> OrderEquipmentAsync(OrderEquipmentGroup orderEquipGroup)
{
if (ModelState.IsValid)
{
// save stuff here.
using (var memoryStream = new MemoryStream())
{
await orderEquipGroup.FileUpload.FormFile.CopyToAsync(memoryStream);
// Upload the file if less than 2 MB
if (memoryStream.Length < 2097152)
{
//var file = new AppFile()
//{
// Content = memoryStream.ToArray()
//};
//_dbContext.File.Add(file);
//await _dbContext.SaveChangesAsync();
}
else
{
ModelState.AddModelError("File", "The file is too large.");
}
}
My last suggestion is that you be VERY careful when uploading files to a server. As Microsoft says in their article, here are some wise guidelines: 1. use a safe filename, 2. allow only approved file extensions, 3. limit the filesize, 4. Scan the uploaded file before saving.

Why Database Storing [object object] type

I'm trying to uplode File along with some columns.File Uploading sucessfully but why Remaining column taking [object object] type
Table
public partial class CreateUserIdentity
{
public int Id { get; set; }
public string Email { get; set; }
public string Image { get; set; }
public string password { get; set; }
}
AngularJs
var description = {
Passwoed: $scope.FileDescription,
Email : $scope.Email
}
FileUploadService.UploadFile($scope.SelectedFileForUpload, description
).then(function (d) {
});
Mvc Controller
[HttpPost]
public JsonResult SaveFiles(string description)
{
if (Request.Files != null)
{
CreateUserIdentity f = new CreateUserIdentity
{
Image = actualFileName,
Email = description,
};
using (ProjectsEntities dc = new ProjectsEntities())
{
dc.CreateUserIdentities.Add(f);
dc.SaveChanges();
Message = "File uploaded successfully";
flag = true;
}
}
return new JsonResult { Data = new { Message = Message, Status = flag } };
The description you are sending is not a string - it is an object consisting of Email and Passwoed - type that correctly in your rest-controller and use Email = description.Email
Alertatively you can just send $scope.Email from the angular-side instead of wrapping it in a description-Object, that should work as well (if you don't need the attribute Passwoed).

How to save FormData into sql

I need to store the path of the file along with its properties into a sql database. Currently all I can do is store the file on the server. I can see the file properties in the controller but I do not know how to access them.
public class File
{
public int FileId { get; set; }
public string FileType { get; set; }
public string FileDate { get; set; }
public string FilePdf { get; set; }
public string FileLocation { get; set; }
public string FilePlant { get; set; }
public string FileTerm { get; set; }
public DateTime? FileUploadDate { get; set; }
public string FileUploadedBy { get; set; }
public string CompanyName { get; set; }
public virtual ApplicationUser User { get; set; }
}
Controller
[HttpPost]
public async Task<HttpResponseMessage> PostFile()
{
if (!Request.Content.IsMimeMultipartContent())
{
this.Request.CreateResponse(HttpStatusCode.UnsupportedMediaType);
}
string root = HttpContext.Current.Server.MapPath("~/App_Data");
var provider = new MultipartFormDataStreamProvider(root);
var result = await Request.Content.ReadAsMultipartAsync(provider);
foreach (var key in provider.FormData.AllKeys)
{
foreach (var val in result.FormData.GetValues("companyname")
.FirstOrDefault())
{
if (key == "companyName")
{
var companyName = val;
var fileDate = val;
var fileLocation = val;
var filePlant = val;
var fileTerm = val;
var fileType = val;
var fileUploadDate = val;
var fileUploadedBy = val;
}
}
}
// On upload, files are given a generic name like "BodyPart_26d6abe1-3ae1-416a-9429-b35f15e6e5d5"
// so this is how you can get the original file name
var originalFileName = GetDeserializedFileName(result.FileData.First());
var uploadedFileInfo = new FileInfo(result.FileData.First().LocalFileName);
string path = result.FileData.First().LocalFileName;
//Do whatever you want to do with your file here
//db.Files.Add();
db.SaveChanges();
return this.Request.CreateResponse(HttpStatusCode.OK, originalFileName);
}
private string GetDeserializedFileName(MultipartFileData fileData)
{
var fileName = GetFileName(fileData);
return JsonConvert.DeserializeObject(fileName).ToString();
}
public string GetFileName(MultipartFileData fileData)
{
return fileData.Headers.ContentDisposition.FileName;
}
Try using a function like this. You can replace with
private object GetFormData<T>(MultipartFormDataStreamProvider result)
{
if (result.FormData.HasKeys())
{
var unescapedFormData = Uri.UnescapeDataString(result.FormData
.GetValues(0).FirstOrDefault() ?? String.Empty);
if (!String.IsNullOrEmpty(unescapedFormData))
return JsonConvert.DeserializeObject<T>(unescapedFormData);
}
return null;
}
Use it like this
File file = GetFormData(result);
The main line of code you want is:
JsonConvert.DeserializeObject<File>(result.FormData.GetValues(0).FirstOrDefault());

Powerpacks DataRepeater Control - Image not getting loaded in picture box

I have a winform powerpacks datareapter control having a picture box. This is the code snippet from the classes.
DisplaySystemUsersControl.Designer.cs
this.picBoxUserImage.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D;
this.picBoxUserImage.DataBindings.Add(new System.Windows.Forms.Binding("Image", this.UserBindingSource, "User_Image", true));
this.picBoxUserImage.Location = new System.Drawing.Point(3, 3);
this.picBoxUserImage.Name = "picBoxUserImage";
this.picBoxUserImage.Size = new System.Drawing.Size(100, 93);
this.picBoxUserImage.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage;
this.picBoxUserImage.TabIndex = 0;
this.picBoxUserImage.TabStop = false;
this.picBoxUserImage.Click += new System.EventHandler(this.picBoxUserImage_Click);
DisplaySystemUsersControl.cs
public DisplaySystemUsersControl()
{
InitializeComponent();
this.dataRepeaterAccounts.DataSource = this.UserBindingSource;
LoadAccountData();
}
private void LoadAccountData()
{
SystemUserBusinessClass oSystemUserBusinessClass = new SystemUserBusinessClass();
List<SystemUserEntity_Only_For_UI_Binding> obj = oSystemUserBusinessClass.GetSystemUsersForUI();
BindingSource tempUserBindingSource = (BindingSource)dataRepeaterAccounts.DataSource;
obj.ForEach(oSystemUserEntity_Only_For_UI_Binding => tempUserBindingSource.Add(oSystemUserEntity_Only_For_UI_Binding));
}
SystemUserEntity_Only_For_UI_Binding.cs
public class SystemUserEntity_Only_For_UI_Binding
{
public string User_Id { get; set; }
public string User_Name { get; set; }
public byte[] User_Image { get; set; }
}
User ID and User name is getting loaded. But Image is not getting loaded. SystemUserEntity_Only_For_UI_Binding.User_Image() is holding the image byte array.
Can anybody please tell me what is going wrong?
Your class should look something like this:
public class SystemUserEntity_Only_For_UI_Binding
{
public string User_Id { get; set; }
public string User_Name { get; set; }
public Image User_Image { get; set; }
}
The byte array needs to be translated into an image somewhere in your code:
using (MemoryStream ms = new MemoryStream(imgBytes)) {
this.User_Image = Image.FromStream(ms);
}
public void BindRepeater (DataSet dsObj)
{
pictureBox1.DataBindings.Clear();
pictureBox1.DataBindings.Add("ImageLocation", dt, "Photo");
dataRepeater1.DataSource = dsObj;
}

Resources