I want to upload the excel file to the Upload folder. But I have set the path properly in my controller, no idea how this error can be happen. Attached the controller code and error screen shot.
Controller code
[HttpPost]
public ActionResult UploadBatch(LogonUser logonUser, IEnumerable<HttpPostedFileBase> files)
{
JsonResultModel result = new JsonResultModel();
RegexUtilities util = new RegexUtilities();
try
{
foreach (HttpPostedFileBase file in files)
{
string fileName = Path.GetFileName(file.FileName);
string upDir = Path.Combine(Request.PhysicalApplicationPath, "Upload", DateTime.Now.ToString("HHmmss"));
string path = Path.Combine(upDir, fileName);
file.SaveAs(path);
}
}
catch (Exception ex)
{
result.Status = JsonResultStatus.Failed;
result.Message = ex.Message;
}
}
Error screenshot:
Related
I want fill form which have upload profile image and other controls like Name,address
I am using angular 8 for client side and asp.net core for backend..
I want viewmodel which contains all properties.
I have used angular8 for uploading image in formdata.I have gone through https://www.techiediaries.com/angular-formdata/.My main question is how to receive uploaded file in ViewModel not in httpRequest.Form.Files["ImageFile"]
[HttpPost("Create")]
public IActionResult CreateApplication(ApplicationModel model)
{
//want to capture uploaded image
return Ok();
}
See this tutorial, can be very helpful: Click
Here is way how i`d do it:
[HttpPost]
public async Task<IActionResult> AddBodyType([FromForm]ApplicationModel model)
{
try
{
if (!ModelState.IsValid)
{
return BadRequest();
}
else
{
var file = Request.Form.Files[0];
var folderName = Path.Combine("Resources", "Images");
var pathToSave = Path.Combine(Directory.GetCurrentDirectory(), folderName);
if (file.Length > 0)
{
var fileName = ContentDispositionHeaderValue.Parse(file.ContentDisposition).FileName.Trim('"');
var fullPath = Path.Combine(pathToSave, fileName);
var dbPath = Path.Combine(folderName, fileName);
using (var stream = new FileStream(fullPath, FileMode.Create))
{
file.CopyTo(stream);
await stream.FlushAsync();
}
model.ImagePath = dbPath;
await _context.Add(model);
return Ok();
}
else
{
return BadRequest();
}
}
}
catch (Exception ex)
{
return StatusCode(500, $"Internal server error: {ex}");
}
}
Ok got it, the problem was that the directory names were not fixed, they were created by the newly created Id of the product, so the solution was to carry out a check for the directory and if it's not there, create it.
For example
if (!Directory.Exists(folderName))
{
Directory.CreateDirectory(folderName);
}
Once it's created with the new Id it can be used/found.
I'm using Xamarin.Forms and I am trying to convert an html string to a pdf file using EvoPdfConverter, but the problem is that when I try to do so, on the line htmlToPdfConverter.ConvertHtmlToFile(htmlData, "", myDir.ToString()); in the code snippet below, the app just freezes and does nothing, seems like it wants to connect to the given IP, but it can't, however I don't get any errors or exceptions! not even catch!! does anybody know what I should do to resolve this issue? and here is my code for this:
public void ConvertHtmlToPfd(string htmlData)
{
ServerSocket s = new ServerSocket(0);
HtmlToPdfConverter htmlToPdfConverter = new
HtmlToPdfConverter(GetLocalIPAddress(),(uint)s.LocalPort);
htmlToPdfConverter.TriggeringMode = TriggeringMode.Auto;
htmlToPdfConverter.PdfDocumentOptions.CompressCrossReference = true;
htmlToPdfConverter.PdfDocumentOptions.PdfCompressionLevel = PdfCompressionLevel.Best;
if (ContextCompat.CheckSelfPermission(Android.App.Application.Context, Manifest.Permission.WriteExternalStorage) != Permission.Granted)
{
ActivityCompat.RequestPermissions((Android.App.Activity)Android.App.Application.Context, new String[] { Manifest.Permission.WriteExternalStorage }, 1);
}
if (ContextCompat.CheckSelfPermission(Android.App.Application.Context, Manifest.Permission.ReadExternalStorage) != Permission.Granted)
{
ActivityCompat.RequestPermissions((Android.App.Activity)Android.App.Application.Context, new String[] { Manifest.Permission.ReadExternalStorage }, 1);
}
try
{
// create the HTML to PDF converter object
if (Android.OS.Environment.IsExternalStorageEmulated)
{
root = Android.OS.Environment.ExternalStorageDirectory.ToString();
}
htmlToPdfConverter.LicenseKey = "4W9+bn19bn5ue2B+bn1/YH98YHd3d3c=";
htmlToPdfConverter.PdfDocumentOptions.PdfPageSize = PdfPageSize.A4;
htmlToPdfConverter.PdfDocumentOptions.PdfPageOrientation = PdfPageOrientation.Portrait;
Java.IO.File myDir = new Java.IO.File(root + "/Reports");
try
{
myDir.Mkdir();
}
catch (Exception e)
{
string message = e.Message;
}
Java.IO.File file = new Java.IO.File(myDir, filename);
if (file.Exists()) file.Delete();
htmlToPdfConverter.ConvertHtmlToFile(htmlData, "", myDir.ToString());
}
catch (Exception ex)
{
string message = ex.Message;
}
}
Could you try to set a base URL to ConvertHtmlToFile call as the second parameter? You passed an empty string. That helps to resolve the relative URLs found in HTML to full URLs. The converter might have delays when trying to retrieve content from invalid resources URLs.
I am trying to download a .csv file on clicking the Download button in my jsp.The jsp code is like following......
<form:form method="POST" id="poCSVForm"
action="downloadPoCsv" commandName="poCSVcmd" modelAttribute="poCSVcmd">
<div class="content">
<fieldset>
<legend>Page Name</legend>
<div>
<div class="contentpane">
<table>
<tr>
<td><button type="submit" value="Download" id="downId" class="dwnldbtn">Download</button>
<button type="button" class="exit smallbtn" value="Exit">Exit</button></td>
</tr>
</table>
</div>
</div>
</fieldset>
</div>
</form:form>
Then my controller code is like this......
#RequestMapping(value = "/downloadPoCsv", method = RequestMethod.POST)
public void doPoCsvDownload(
#ModelAttribute("poCSVcmd") PurchaseOrderCSVBean poCsvBean,
Map<String, Object> model, HttpServletRequest req,HttpServletResponse response) throws IOException {
CSVWriter writer = null;
String filepath = null;
try {
HttpSession session = req.getSession();
Session hsession = (Session) session
.getAttribute(MOLConstants.HIBERNATE_SESSION_KEY);
filepath = "purchaseOrder" + new Date().getTime() + ".csv";
ServletContext context = req.getServletContext();
String realPath = context.getRealPath("");
System.out.println("appPath = " + realPath);
// construct the complete absolute path of the file
String fullPath = realPath + "\\stuff\\" + filepath;
System.out.println("fullPath = " + fullPath);
File downloadFile = new File(realPath);
try {
if (!downloadFile.exists()) {
if (downloadFile.mkdir()) {
} else {
throw new RuntimeException("Could not create directory");
}
}
} catch (Exception e) {
throw new RuntimeException();
}
String mimeType = context.getMimeType(fullPath); // get MIME type of the file
if (mimeType == null) {
mimeType = "application/octet-stream"; // set to binary type if MIME mapping not found
}
System.out.println("MIME type: " + mimeType);
// set content attributes for the response
response.setContentType(mimeType);
response.setContentLength((int) downloadFile.length());
// set headers for the response
String headerKey = "Content-Disposition";
String headerValue = String.format("attachment; filename=\"%s\"",downloadFile.getName());
response.setHeader(headerKey, headerValue);
List<PoCsvUploadView> csvDataList = poService.getPoCsvData(poCsvBean.getExp_ind(),poCsvBean.getStdt(),poCsvBean.getEnddt());
FileWriter fwriter = new FileWriter(fullPath);
writer = new CSVWriter(fwriter, ',', CSVWriter.NO_QUOTE_CHARACTER);
String[] header = new String[31];
header[0] = "COMPANY_CD";
.......
header[30] = "VENDOR_TYPE";
List<String[]> li = new ArrayList<String[]>();
li.add(header);
for (PoCsvUploadView group : csvDataList)
{
String[] arr = new String[31];
arr[0] = group.getCompany_cd();
.....
arr[30] = group.getVendor_type();
li.add(arr);
}
writer.writeAll(li);
} catch (Exception e) {
e.printStackTrace();
logger.error("Exception >> ", e);
throw new CustomGenericException(
"Error occured while loading report!!");
}finally{
writer.flush();
writer.close();
}
}
Now When I am click on the download button, the csv file is being generated at the specific location ie on fullPath variable. But that file is not downloading through the browser, instead of that browser is downloading some file named downloadPoCsv(which is exactly same as my #RequestMapping in my controller method), which is not desired. Can you guys provides some help on this. Thanx in advance.And yes I am using OpenCsv jar.
To be clear here the issue is spring MVC not openCSV because your problem description is that you are trying to download a file and it is downloading a file with a different name.
CodeJava has a pretty good example of a Spring MVC download. Give that a try.
I am uploading a profile picture of a user to a folder and saving its path to RavenDB. But my code is giving me an error that part of path is not found. On this line
file.SaveAs(path);
Code:
[HttpPost]
public ActionResult UploadPic(FileManagement fmanage, HttpPostedFileBase file)
{
string email = User.Identity.Name;
if (file != null && file.ContentLength > 0)
{
var FileName = string.Format("{0}.{1}", Guid.NewGuid(), file.ContentType);
var path = Path.Combine(Server.MapPath("~/App_Dta/Uploads"), FileName);
file.SaveAs(path);
using (var session = DocumentStore.OpenSession("RavenMemberShip"))
{
var query = from q in Session.Query<Registration>() where q.Email == email select q;
if (query.Count() > 0)
{
foreach (var updated in query)
{
fmanage.FileName = FileName;
fmanage.Path = path;
session.SaveChanges();
}
}
}
}
else ModelState.AddModelError("", "Remove the errors and try again");
return View();
}
You have a typing error in your path...
Replace...
var path = Path.Combine(Server.MapPath("~/App_Dta/Uploads"), FileName);
With...
var path = Path.Combine(Server.MapPath("~/App_Data/Uploads"), FileName);
You also need to make sure you have the relevant permissions to write to this directory.
Based on your error, the filepath looks incorrect.
c:\users\wasfa\documents\visual studio
2012\Projects\MvcMembership\MvcMembership\App_Data\Uploads\daed3def-df2b-4406-aa9e-c1995190aa6d.image\jpeg
is daed3def-df2b-4406-aa9e-c1995190aa6d.image\jpeg the name of the file?
Try:
[HttpPost]
public ActionResult UploadPic(FileManagement fmanage, HttpPostedFileBase file)
{
string email = User.Identity.Name;
if (file != null && file.ContentLength > 0)
{
var FileName = string.Format("{0}.{1}", Guid.NewGuid(), Path.GetFileName(file.FileName));
var path = Path.Combine(Server.MapPath("~/App_Dta/Uploads"), FileName);
file.SaveAs(path);
using (var session = DocumentStore.OpenSession("RavenMemberShip"))
{
var query = from q in Session.Query<Registration>() where q.Email == email select q;
if (query.Count() > 0)
{
foreach (var updated in query)
{
fmanage.FileName = FileName;
fmanage.Path = path;
session.SaveChanges();
}
}
}
}
else ModelState.AddModelError("", "Remove the errors and try again");
return View();
}
Before file.SaveAs(path), try to check directory exist, if not, create one,
if(CreateFolderIfNeeded(path);
{
file.SaveAs(path);
}
A private function to create directory if needed,
private static bool CreateFolderIfNeeded(string path)
{
bool result = true;
if (!Directory.Exists(path))
{
try
{
Directory.CreateDirectory(path);
}
catch (Exception)
{ result = false; }
}
return result;
Hope this helps.
Check the var FileName = string.Format("{0}.{1}", Guid.NewGuid(), file.ContentType); line in your code.
The file.ContentType will not return the extension of the file you are uploading. It shuold be like daed3def-df2b-4406-aa9e-c1995190aa6d.jpeg instead of daed3def-df2b-4406-aa9e-c1995190aa6d.image\jpeg
find the extension from the uploaded file using substring.
Hope this help
public void ZipExtract(string zipfilename, string outputDirectory)
{
using (ZipFile zip = ZipFile.Read(zipfilename))//file not found exception
{
Directory.CreateDirectory(outputDirectory);
zip.ExtractSelectedEntries("name=*.jpg,*.jpeg,*.png,*.gif,*.bmp", " ",
outputDirectory, ExtractExistingFileAction.OverwriteSilently);
}
}
[HttpPost]
public ContentResult Uploadify(HttpPostedFileBase filedata)
{
var path = Server.MapPath(#"~/Files");
var filePath = Path.Combine(path, filedata.FileName);
if (filedata.FileName.EndsWith(".zip"))
{
ZipExtract(filedata.FileName,path);
}
filedata.SaveAs(filePath);
// CreateThumbnail(filePath);
_db.Photos.Add(new Photo
{
Filename = filedata.FileName
});
_db.SaveChanges();
return new ContentResult{Content = "1"};
}
I try to extract the uploaded zip archive and save extracted files in a folder but "file not found" exception happens all the time. What's the mistake?
Have you tried setting a break point here, and see what value filedata.FileName has? (And see if it actually exists on the server.)
if (filedata.FileName.EndsWith(".zip"))
{
ZipExtract(filedata.FileName,path);
}