I Want to download the files present in the Folder i.e App_Data.This file I have saved with GUID but not able to download.
My code is as follows:
public FilePathResult DownLoadDispatch(long CIDInvID)
{
var Attr = db.ConsolidatedInvoiceDispatchDocuments.FirstOrDefault(x => x.ConsolidatedInvoiceDispatchID == CIDInvID);
string path = System.Web.HttpContext.Current.Server.MapPath("~") + "/App_Data/files/Dispatch/" + Attr.StoredName.ToString();
string fileName = Attr.FileName;
return File(path + fileName, "text/plain", "test.txt");
}
Related
My objective is User can choose an image from any place from their desktop and upload/tweet the same to twitter. I'm struggling to set the relative path to the imagePath variable.
The path (D Drive) were my image stored. While running the application it looks in different path. This throws an error System.IO.FileNotFoundException. I tried Server.MapPath too. Assist me to resolve it.
Solved the issue as following
string filePath; string imagePath = "";
if (imgFile == null)
{
imgFile = Request.Files["imgFile"];
}
if (imgFile.FileName != "")
{
filePath = Server.MapPath("~/Images/");
if (!Directory.Exists(filePath))
{
Directory.CreateDirectory(filePath);
}
filePath = filePath + Path.GetFileName(imgFile.FileName);
imgFile.SaveAs(filePath);
imagePath = Path.Combine(Server.MapPath(#"~/Images/"), filePath);
}
File must be saved in the server location, try to replace the below instruction:
string imagePath=Path.Combine(Request.MapPath("~/"),fileName);
with the below instruction
var fileName = Path.GetFileName(file.FileName);
var imagePath = Path.Combine(Request.MapPath("~/"), fileName);
file.SaveAs(imagePath);
........
Cordially
I have the Presentation Web Script (script A) and the Data Web Script (script B).
In the script A I build the dialog that interacts with the script B.
Here I am forming some path where the some file will be uploaded (group, year and number parameters define this path):
...
var submitHandler = function() {
var dataWebScriptUrl = window.location.protocol + '//' +
window.location.host + "/alfresco/s/ms-ws/script-b?guest=true";
var yearCombo = document.getElementById("year");
var year = yearCombo.options[yearCombo.selectedIndex].value;
var groupCombo = document.getElementById("group");
var group = groupCombo.options[groupCombo.selectedIndex].value;
var numberCombo = document.getElementById("number");
var number = numberCombo.value;
var uploadedFile = document.getElementById("uploadedFile");
var file = uploadedFile.files[0];
var formData = new FormData();
formData.append("year", year);
formData.append("group", group);
formData.append("number", number);
formData.append("uploadedFile", file);
var xhr = new XMLHttpRequest();
xhr.open("POST", dataWebScriptUrl);
xhr.send(formData);
};
...
In script B, I'm using the Apache Chemistry OpenCMIS API to create a path in the CMIS-compatible Alfresco repository:
public class CustomFileUploader extends DeclarativeWebScript implements OpenCmisConfig {
...
private void retrievePostRequestParams(WebScriptRequest req) {
String groupName = null, year = null, number = null;
FormData formData = (FormData) req.parseContent();
FormData.FormField[] fields = formData.getFields();
for(FormData.FormField field : fields) {
String fieldName = field.getName();
String fieldValue = field.getValue();
if(fieldName.equalsIgnoreCase("group")) {
if(fieldValue.equalsIgnoreCase("services")) {
groupName = "Услуги";
...
}
firstLevelFolderName = "/" + groupName;
secondLevelFolderName = groupName + " " + year;
thirdLevelFolderName = number;
}
...
Folder firstLevelFolder =
createFolderIfNotExists(cmisSession, docLibFolder, firstLevelFolderName);
...
private Folder createFolderIfNotExists(Session cmisSession,
Folder parentFolder, String folderName) {
Folder subFolder = null;
for(CmisObject child : parentFolder.getChildren()) {
if(folderName.equalsIgnoreCase(child.getName())) {
subFolder = (Folder) child;
}
}
if(subFolder == null) {
Map<String, Object> props = new HashMap<>();
props.put("cmis:objectTypeId", "cmis:folder");
props.put("cmis:name", folderName);
subFolder = parentFolder.createFolder(props);
}
return subFolder;
}
private Folder getDocLibFolder(Session cmisSession, String siteName) {
String path = "/Sites/" + siteName + "/documentLibrary";
return (Folder) cmisSession.getObjectByPath(path);
}
private Session getCmisSession() {
SessionFactory factory = SessionFactoryImpl.newInstance();
Map<String, String> conf = new HashMap<>();
// http://localhost:8080/alfresco/api/-default-/public/cmis/versions/1.1/atom
conf.put(SessionParameter.ATOMPUB_URL, ATOMPUB_URL);
conf.put(SessionParameter.BINDING_TYPE, BindingType.ATOMPUB.value());
conf.put(SessionParameter.USER, USER_NAME);
conf.put(SessionParameter.PASSWORD, PASSWORD);
// "org.alfresco.cmis.client.impl.AlfrescoObjectFactoryImpl"
conf.put(SessionParameter.OBJECT_FACTORY_CLASS, OBJECT_FACTORY_CLASS);
conf.put(SessionParameter.REPOSITORY_ID, "-default-");
Session session = factory.createSession(conf);
return session;
}
...
It's all works well... But I need to create the directory structure on a specific site, e.g. "contracts-site", here:
/site/contracts-site/documentlibrary
When I specifying the following:
/Sites/contracts-site/documentLibrary/Услуги
/Sites/contracts-site/Услуги
/site/contracts-site/documentlibrary/Услуги
I get the following exception (depending on the path):
org.apache.chemistry.opencmis.commons.exceptions.CmisObjectNotFoundException: Object not found: /Sites/contracts-site/Услуги
When I specifying the following:
"/Услуги"
Everything works, but the directory structure is created outside the site...
How to create a folder on the Alfresco site by using OpenCMIS API?
Arn't you missing /company_home/ ?
This would lead to
/company_home/Sites/contracts-site/documentLibrary/Услуги
Just accidentally found the solution. Works perfectly if specify the following path:
// locate the document library
String path = "/Сайты/contracts-site/documentLibrary";
Ie, "Сайты" instead of "Sites"... (Cyrillic alphabet)
I'm using ru_RU locale and UTF-8 encoding. Then this example also works.
I am trying to upload an image from ASP.NET to S3. I am using AWS SDK for that and have already set up what is needed. However, after i run my project, i received an error. I'll be replacing my bucket name to ... for this sample code.
I set up my secretkey and accesskey from User in my Web.config. Please do tell me if u need more codes. I need help.
controller
private static readonly string _awsAccessKey = ConfigurationManager.AppSettings["AWSAccessKey"];
private static readonly string _awsSecretKey = ConfigurationManager.AppSettings["AWSSecretKey"];
[HttpPost]
public ActionResult UploadFile(HttpPostedFileBase file)
{
try
{
if (file.ContentLength > 0)
{
IAmazonS3 client;
using (client = Amazon.AWSClientFactory.CreateAmazonS3Client(_awsAccessKey, _awsSecretKey))
{
PutObjectRequest request = new PutObjectRequest
{
BucketName = "...",
CannedACL = S3CannedACL.PublicRead,
Key = "images/" + (DateTime.Now.ToBinary() + "-" + file.FileName),
FilePath = Server.MapPath("~/UploadedFiles")
};
client.PutObject(request);
}
}
imageUrls = "File Uploaded Successfully!!";
System.Diagnostics.Debug.WriteLine("File Uploaded Successfully!!");
return Json(imageUrls);
}
catch
{
ViewBag.Message = "File upload failed!!";
System.Diagnostics.Debug.WriteLine("File upload failed!!");
return Json(ViewBag.Message);
}
}
You're getting the error due to DateTime.Now.ToBinary() which contains invalid characters to be used in a URL. For example, you could use a GUID or a Unix timestamp instead.
Also, the FilePath property you're assigning to the PutObjectRequest is the full path and name to a file to be uploaded. So, you don't need it when you already have HttpPostedFileBase as an input parameter, which contains the InputStream property (i.e., the stream object).
Your PutObjectRequest should look something like this:
.
.
.
Guid guid = Guid.NewGuid();
// Create a client
AmazonS3Client client = new AmazonS3Client(_awsAccessKey, _awsSecretKey);
// Create a PutObject request
PutObjectRequest request = new PutObjectRequest
{
BucketName = "...",
CannedACL = S3CannedACL.PublicRead,
Key = "images/" + guid + "-" + file.FileName
};
using (System.IO.Stream inputStream = file.InputStream)
{
request.InputStream = inputStream;
// Put object
PutObjectResponse response = client.PutObject(request);
}
.
.
.
I finally solved it. I realized i did not place region in AWSClientFactory, right at the end after the keys.
I am working on an ASP .net webpage which receives a form which is posted to it. The posted form has three as well.
filename = uploadFile(HttpContext.Current.Request.Files["file1"], path);
This is the code through which i upload a file to my server. And this is the code of the function.
public string uploadFile(HttpPostedFile file, string dest)
{
string filename = file.FileName;
string path = Server.MapPath(dest);
String extension = Path.GetExtension(file.FileName);
filename = filename.Replace(extension, "");
filename = filename.Replace(".", "");
filename = System.DateTime.Now.ToString("ddMMyyyyhhmmss") + filename + extension;
string savepath = path + "/" + filename;
file.SaveAs(savepath);
return filename;
}
The problem is I am not able to check if file1 from the posted form actually has file. Is it possible?
Use the FileUpload control in conjunction with the HasFile property:
FileUpload.HasFile Property
If you have to do it that way, you can simply check if the ContentLength is greater than zero.
I need to create zip file from the folder, path:
D:\Nagaraj\New Project Read Document\TCBILPOS\TCBILPOS\TCBILPOS\FileBuild\HOST
within that host folder there are 7 txt files.
I want to create zip file HOST.zip in the folder above:
D:\Nagaraj\New Project Read Document\TCBILPOS\TCBILPOS\TCBILPOS\FileBuild
I've used Ionic ZIP for this in our own projects.
using (ZipFile zip = new ZipFile())
{
// add this map file into the "images" directory in the zip archive
zip.AddFile("c:\\images\\personal\\7440-N49th.png", "images");
// add the report into a different directory in the archive
zip.AddFile("c:\\Reports\\2008-Regional-Sales-Report.pdf", "files");
zip.AddFile("ReadMe.txt");
zip.Save("MyZipFile.zip");
}
public class Ziper
{
public static string MapPathReverse(string fullServerPath)
{
return #"~\" + fullServerPath.Replace(HttpContext.Current.Request.PhysicalApplicationPath, String.Empty);
}
public static void Zip(HttpResponse Response, HttpServerUtility Server, string[] pathes)
{
Response.Clear();
Response.BufferOutput = false; // false = stream immediately
System.Web.HttpContext c = System.Web.HttpContext.Current;
//String ReadmeText = String.Format("README.TXT\n\nHello!\n\n" +
// "This is text for a readme.");
string archiveName = String.Format("archive-{0}.zip",
DateTime.Now.ToString("yyyy-MMM-dd-HHmmss"));
Response.ContentType = "application/zip";
Response.AddHeader("content-disposition", "filename=" + archiveName);
var path = Server.MapPath(#"../Images/TempFile/TempFile" + DateTime.Now.Ticks);
if (Directory.Exists(path) == false)
Directory.CreateDirectory(path);
var pathzipfile = Server.MapPath(#"../Images/TempFile/zip_" + DateTime.Now.Ticks + ".zip");
for (int i = 0; i < pathes.Length; i++)
{
if (File.Exists(pathes[i]))
{
string dst = Path.Combine(path, Path.GetFileName(pathes[i]));
File.Copy(pathes[i], dst);
}
}
if (File.Exists(pathzipfile))
File.Delete(pathzipfile);
ZipFile.CreateFromDirectory(path, pathzipfile);
{
byte[] bytes = File.ReadAllBytes(pathzipfile);
Response.OutputStream.Write(bytes, 0, bytes.Length);
}
Response.Close();
File.Delete(pathzipfile);
Directory.Delete(path, true);
}
public Ziper()
{
}
}