How to make file uploading optional using Mvc 4 - asp.net-mvc

I am uploading 3 types of files, i.e 1)video 2)image 3)document.
if i am uploading all three files at once so it is upload and show successfully, but if i want to skip one the file of uploading then it giving me following errors. Please Help me here:
httpPostedFile.SaveAs(fileSavePath);
db.SaveChanges();
one the errors is because of sending path to db i guess.
[HttpPost]
public ActionResult AddSKU(SKU_Det skufiles, IEnumerable<HttpPostedFileBase> files)
{
var httpPostedFile = Request.Files[0];
if (httpPostedFile != null)
{
var uploadFilesDir = System.Web.HttpContext.Current.Server.MapPath("~/Content/Videos");
if (!Directory.Exists(uploadFilesDir))
{
Directory.CreateDirectory(uploadFilesDir);
}
var fileSavePath = Path.Combine(uploadFilesDir, httpPostedFile.FileName);
httpPostedFile.SaveAs(fileSavePath);
}
foreach (var file in files)
{
if (file != null && file.ContentLength > 0)
{
file.SaveAs(HttpContext.Server.MapPath("~/Areas/Admin/Images/") + file.FileName);
}
}
SKU_Det sku = new SKU_Det();
sku.SKU = skufiles.SKU;
sku.VideoPath = Request.Files[0].FileName;
sku.Imagepath = sku.FilePath = Request.Files[1].FileName;
sku.FilePath = sku.FilePath = Request.Files[2].FileName;
db.SKU_Det.Add(sku);
db.SaveChanges();

Related

asp.net MVC upload file with subfolder path using DropZone

Assalamualaikum,
in ASP.NET MVC, I can upload file by DropZone. Here, if I drag and drop any folder contains sub folders and file, it upload only all files from all sub folder, in a server upload folder. But I want to upload those file with its sub folder name. This sub folder name can be store in DB or create new folder.
For example uploading file / folder in google drive.
Here is my uploading code (Only the functional code here) :
public void Upload()
{
bool isSavedSuccessfully = true;
string fName = "";
try
{
foreach (string fileName in Request.Files)
{
HttpPostedFileBase file = Request.Files[fileName];
fName = file.FileName;
if (file != null && file.ContentLength > 0)
{
try
{
Guid GuidFileName = Guid.NewGuid();
var path = Path.Combine(Server.MapPath("~/_UploadedFile"));
string pathString = System.IO.Path.Combine(path.ToString());
var fileName1 = Path.GetFileName(file.FileName);
var ext = Path.GetExtension(file.FileName);
bool isExists = System.IO.Directory.Exists(pathString);
if (!isExists) System.IO.Directory.CreateDirectory(pathString);
var uploadpath = string.Format("{0}\\{1}{2}", pathString, GuidFileName.ToString(), ext.ToString());
file.SaveAs(uploadpath);
}
catch (Exception ex)
{
}
}
}
}
catch (Exception ex)
{
isSavedSuccessfully = false;
}
if (isSavedSuccessfully)
{
}
else
{
}
}
Now, please help me to get sub folder's name from file.
Thanks.

Wrong Mimetype for .RTF in web request

When a .rtf file is upload through an action in ASP.NET MVC, the mimetype for seems to be wrong (application/msword instead of application/rtf):
foreach (string _file in Request.Files)
{
var fileContent = Request.Files[_file];
if (fileContent != null && fileContent.ContentLength > 0)
{
var stream = fileContent.InputStream;
Attachment attachment = new Attachment
{
File = stream.ToByteArray(),
MimeType = fileContent.ContentType,
NomeFile = fileContent.FileName,
Description = description
};
}
}
fileContent is HttpPostedFileBase type.

Multiple Excel upload error in ExcelPackage EPPlus

public ActionResult ExcelFile(IEnumerable < HttpPostedFileBase > excelFile) {
try {
if (excelFile != null) {
foreach(var singleExcel in excelFile) {
string path = "~/ExcelFolder/";
singleExcel.SaveAs(Server.MapPath(path + singleExcel.FileName));
using(FileStream fs = new FileStream(Server.MapPath(path + singleExcel.FileName), FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) {
using(ExcelPackage package = new ExcelPackage(fs)) {
ExcelWorksheet sheet = package.Workbook.Worksheets[1];
int startRowNumber = sheet.Dimension.Start.Row;
int endRowNumber = sheet.Dimension.End.Row;
int startColumnNumber = sheet.Dimension.Start.Column;
int endColumnNumber = sheet.Dimension.End.Column;
if (endColumnNumber > 26) {
for (int currentColumnNumber = endColumnNumber; startColumnNumber < currentColumnNumber; currentColumnNumber--) {
var cellValue = sheet.Cells[startRowNumber, currentColumnNumber].Value ? .ToString();
if (!string.IsNullOrWhiteSpace(cellValue)) {
if (cellValue == "延人公里小計") {
sheet.DeleteColumn(currentColumnNumber);
sheet.Cells[1, currentColumnNumber].Value = "小計";
//return fsr;
package.SaveAs(
new FileInfo(# "C:\Users\leon0944\Desktop\123\" + singleExcel.FileName));
break;
}
}
}
}
}
}
}
Hello,when I upload many Excel to the file then read every single Excel to do someting.then i got error in ExcelPackage package = new ExcelPackage(fs) this row
error message :System.Runtime.InteropServices.COMException: HRESULT:
0x8003001D (STG_E_WRITEFAULT)
sometime is working normally sometime I got error,Please tell me How Can I fix this. The problem existed for several days.

asp.net mvc 5 sent email attachments are damaged

I am trying to send an email using the method described in this tutorial with a model structure form this tutorial and im partially successfull in doing so. The only issue I am having is the fact that files sent as attachments are damaged. I have tried to get it working in so many ways that I lost count. Obviously haven't been trying hard enough since I didn't find the answer, but decided to ask while I continue looking for an answer.
My controller action is as follows:
public async Task<ActionResult> Index( [Bind(Include = "column names..")] Contact contact, HttpPostedFileBase upload){
if (ModelState.IsValid && status)
{
var message = new MailMessage();
if (upload != null && upload.ContentLength > 0)
{
// 4MB -> 4000 * 1024
const int maxFileSize = 4096000;
if (upload.ContentLength < maxFileSize)
{
var document = new File
{
FileName = System.IO.Path.GetFileName(upload.FileName),
FileType = FileType.Document,
ContentType = upload.ContentType
};
var supportedTypes = new[] {"doc", "docx", "pdf", "jpg"};
var extension = System.IO.Path.GetExtension(document.FileName);
if (extension != null)
{
var fileExt = extension.Substring(1);
if (!supportedTypes.Contains(fileExt))
{
ModelState.AddModelError("document", "Wrong format");
return View();
}
//this is the line that sends damaged attachments,
//I believe I should be using document in some way (using reader bit below),
//but whatever I use the code complains or crashes.
message.Attachments.Add(new Attachment(upload.InputStream, Path.GetFileName(upload.FileName)));
using (var reader = new System.IO.BinaryReader(upload.InputStream))
{
document.Content = reader.ReadBytes(upload.ContentLength);
//message.Attachments.Add(new Attachment(document.Content, document.FileName));
}
contact.Files = new List<File> {document};
}
}else
{
ModelState.AddModelError("document", "File too big. Max 4MB.");
}
}
EDIT: A lot of times the code cannot find the file, how do I make sure I give it correct path each time?

Error in File downloading file from a folder in MVC2

I am encountering a problem in getting the download prompt. In the below code first am allowing the user to upload a file to compress. Once the file is compressed the user should be provided with the compressed files. But in the below code download prompt doesn't appears neither it shows any error. Please help me by correcting my code
The view code:
function CompressFile(box) {
var file = document.getElementById('fileComp');
if (file.value == "") {
alert("Choose a file to upload");
return false;
}
dhtmlx.modalbox.hide(box);
var fd = new FormData();
fd.append('file', file.files[0]);
var xhr = new XMLHttpRequest();
xhr.open('POST', '/FileUpload/Compress', true);
xhr.send(fd);
}
The controller code:
public ActionResult Compress(HttpPostedFileBase file)
{
var supportedType = new[] { "pdf" };
var fileExt = System.IO.Path.GetExtension(file.FileName).Substring(1);
var filename = Path.GetFileNameWithoutExtension(file.FileName) ?? "";
if (file.ContentLength > 0 && supportedType.Contains(fileExt))
{
string filePath = Path.Combine(HttpContext.Server.MapPath(_uploadPDF), Path.GetFileName(file.FileName));
file.SaveAs(filePath);
PdfReader reader = new PdfReader(filePath);
string name = DateTime.Now.ToString("ddMM_HHmmss");
name = Server.MapPath(_fileUploadPath + name + ".pdf");
PdfStamper stamper = new PdfStamper(reader, new FileStream(name, FileMode.Create), PdfWriter.VERSION_1_5);
stamper.FormFlattening = true;
stamper.SetFullCompression();
stamper.Close();
string fn = System.IO.Path.GetFileName(name);
return base.File(name, "application/pdf",fn);
}
else
{
return View();
}
}
The problem is that you're using Ajax. You can't download a file through Ajax. You need to do a regular POST to the ActionMethod. That way the browser can send you back the file and prompt the user where he wants to save it.

Resources