How to upload a local file as link in asp.net - html

I want to know how to add a local file path as a link and after adding it i want to download the file while clicking the link in asp.net.
My code:
<a href="D:/Sample/test.html" runat="server">
Here i just add my local path to the server.But here nothing done while clicking the link. I want to use .zip file instead of .html file.Let me know how to upload and download by using a link.Thanks in advance

I fail to see the problem here. Just add "~/" to find file from the root of your project and add runat="server" to the anchor link:
Download Zip File
You need to resolve it from the root because while you may know that it's on the D drive on your local machine, you cannot be sure that will be the same on the server. And even if it is on the same drive on the server, what if someone migrates it later on?
As for uploading a file, simply use the Upload control?

There are lots of situation, Using this code you can do it.
File Upload Code
string FilePath = "";
string[] a = new string[1];
string fileName = "";
string FullName = "";
if (FileUploader.FileName.Length > 0)
{
a = FileUploader.FileName.Split('.');
fileName = Convert.ToString(System.DateTime.Now.Ticks) + "." + a.GetValue(1).ToString();
FilePath = Server.MapPath(#"~\SavedFolder");
Fup1.SaveAs(FilePath + #"\" + fileName);
FullName = FilePath + #"\" + fileName;
// Database Saved Code
}
File Download Code
string filename = "filename from Database";
Response.ContentType = "application/octet-stream";
Response.AppendHeader("Content-Disposition", "attachment;filename=" + filename);
string aaa = Server.MapPath("~/SavedFolder/" + filename);
Response.TransmitFile(Server.MapPath("~/SavedFolder/" + filename));
Response.End();

Related

Uploading files on Webapp into Docker container

I have been googling constantly and can't seem to find an answer for this. My apologies if it's a noob question as I am still extremely new to Docker.
Scenario:
I have a dockerized web app with a NodeJS backend. On the website, I need to be able to upload files and store the path to them in the database (MSSql Database container). When I upload files using multiparty on the Node end, it gives it the temp path for files. On Windows, its ...../AppData/Local/Temp/.... On Linux, it looks to be /tmp/... Then, I use this path as a link to open the file from a different page. On Windows, running the app locally (no dockerizing), I can access the file (excluding Chrome's security features that prevent the download). However, on Linux and dockerized, there is no file. I will attach my file uploading code at the bottom.
I know that docker containers do not talk to the host's file system like a normal web application. My file isn't being stored in the /tmp folder as I've already checked there. My guess is that it is somehow storing it within the container.
My confusion lies with how to store these files. Volumes seem to be for loading files into containers and storage drivers don't seem to be something you can mess with other than to configure them (I am using overlay2 if it matters). How do I store the uploaded files within my container so that I can store their path and access them again later?
var app = express();
app.post("/api/files", function(req, res) {
var form = new multiparty.Form();
form.parse(req, function(err, fields, files) {
var dict = files.Contents[0];
console.log(dict);
var query = "EXECUTE CTF.dbo.CTF_CreateFilesSp " + fields.ID + ", '" + dict["originalFilename"] + "', '" + dict["path"] + "'";
executeQuery(query, res);
});
});
UPDATE:
I was able to get a volume/bind mount set up for my container using:
volumes:
- /var/opt/tmp:/var/opt/tmp
and I updated my parsing method to this:
app.post("/api/files", function(req, res) {
var form = new multiparty.Form();
var target_path = '';
form.on('file', function(name, file) {
var tmp_path = file.path;
target_path = '/var/opt/tmp/' + file.originalFilename;
fs.copyFile(tmp_path, target_path, function(err) {
if (err) console.error(err.stack);
else console.log(target_path);
})
});
form.parse(req, function(err, fields, files) {
var dict = files.Contents[0];
var query = "EXECUTE CTF.dbo.CTF_CreateFilesSp " + fields.ID + ", '" + dict["originalFilename"] + "', '" + target_path + "'";
executeQuery(query, res);
});
});
When I upload the file, I do see a copy of this show up in the host's directory as expected. However, when I click the link to the file on an html page, using the full path /var/opt/tmp/FILENAME, it says cannot GET /var/opt/tmp/FILENAME.
I'm sure this has to do with incorrect permissions or href in my html, but I'm not sure. I'm very new to web development.
How do I get the link on an html page to download this file from the directory? Please let me know if this is out of the scope of the original question and I'll make a new one.

Flying Saucer - Open an attachment from pdf link

I would like to know if there is a way to create a link (Using HTML) to open an attachment embedded in the pdf document.
Something like this...
Open the attachment file or Open the attachment file
Any suggestion or recommendation?
Thanks
I have been able to implement this scenario after reading the next useful post
https://groups.google.com/forum/#!topic/flying-saucer-users/KuwPoTjaQYU
Steps:
Check out the next repository https://github.com/osnard/flyingsaucer
Analyse the file ITextOutputDevice.java, method processLink(RenderingContext c, Box box)
Make changes based on your needs
Build the project and use the jar file generated
Here the code to create an embedded file based on base64 content.
Java
...String doEmbedFile = handler.getAttributeValue( elem, "data-fs-embed-file" );
if ("true".equals(doEmbedFile.toLowerCase())) {
String fileName = new File(uri).getName();
String content = handler.getAttributeValue( elem, "content" );
com.lowagie.text.Rectangle targetArea = checkLinkArea(c, box);
if (targetArea == null) {
return;
}
try {
if (!_attachments.contains(fileName)) {
byte[] fileBytes = Base64.getDecoder().decode(content.getBytes("UTF-8"));
PdfFileSpecification fs = PdfFileSpecification.fileEmbedded(_writer, null, fileName, fileBytes);
fs.addDescription(fileName, true);
_writer.addFileAttachment(fs);
_attachments.add(fileName);
}
targetArea.setBorder(0);
targetArea.setBorderWidth(0);
//This only works on Adobe Acrobat Reader
PdfAction action = PdfAction.javaScript(
"this.exportDataObject({cName:\"" + fileName + "\", nLaunch:2});",
_writer
);...
HTML
<body><div id='div1'><p><a href='test.png' data-fs-embed-file='true' content='iVBORw0KGgoAAAANSUhEU...'>open test.png file</a></p></div><div id='div2'><p><a href='test.pdf' data-fs-embed-file='true' content='JVBERi0xLjUNCiW1tbW1D...'>open test.pdf file</a></p></div><div id='div3'><p><a href='test.txt' data-fs-embed-file='true' content='VEVFRUVFRUVFRVNUIFRYVA=='>open test.txt file</a></p></div></body>
*base64 content truncated
Output
Greetings and I hope it can help others
just open it on new tab, add attribute target="_blank" in your anchor tag
Open attachment

how to get a image link that can be put in a html code from dropbox api?

try {
Path temp = Files.createTempFile(filename + "-", "." + extension);
file = temp.toFile();
//file = File.createTempFile(filename + "-", "." + extension, tempfolder);
try (InputStream input = event.getFile().getInputstream()) {
Files.copy(input, temp, StandardCopyOption.REPLACE_EXISTING);
}
FileInputStream inputStream = new FileInputStream(file);
try {
DbxEntry.File uploadedFile = client.uploadFile("/"+filename,
DbxWriteMode.add(), file.length(), inputStream);
System.out.println("Uploaded: " + uploadedFile.toString());
String fileurl = client.createShareableUrl("/"+filename);
System.out.println(fileurl);
//insertFileLink(fileurl);
} finally {
inputStream.close();
}
file.deleteOnExit();
} catch (IOException e) {
e.printStackTrace(); //log this
status="Failure";
message = event.getFile().getFileName() + "is not uploaded.Try again.";
}
I can get links like below with the help of the code piece above:
https://www.dropbox.com/s/asqjcgnu5fjn2a8/photo?dl=0
Basically my goal is, when someone upload a photo to my website, I will store the actual file in Dropbox, and the link of the file in my database.
I will give this link to my html files and it will be shown in the website user interface. For example someone's profile picture.
The links that I want should be like this: http://i.imgur.com/TRr3u73.jpg
Hope I am clear.
Is there a way to get such links using Dropbox API?
You're almost there with your existing code. Try adding the query parameter raw=1 to the URL, but also make sure the file name has a good extension. (You won't be able to view the example image you gave in the browser, since Dropbox doesn't know it's an image.)
See https://www.dropbox.com/help/201 for details about viewing share links.

Webmatrix - WebImage helper and Create Directory

I have previously successfully managed to upload a file using the webimage helper, but i am now trying to combine that with creating a directory, and failing miserably. here is my code:
if(IsPost){
//Create Directory using PropertyID
var imageroot = Server.MapPath("~/Images/Property/");
var foldername = rPropertyId.ToString();
var path = Path.Combine(imageroot, foldername);
if(!Directory.Exists(path)){
Directory.CreateDirectory(path);
}
photo = WebImage.GetImageFromRequest();
if(photo != null){
MediumFileName = rPropertyId + "_" + gooid + "_" + "Medium";
imagePath = path + MediumFileName;
photo.Save(#"~\" + imagePath);}
}
First, i create a directory with the name of the propertyID. This works fine. I then try and upload new photo's into that path, and i get an error saying that "The given path's format is not supported".
Any ideas?
You correctly use Path.Combine() when creating the directory path, you should do the same when making the image path.
imagePath = Path.Combine(path, MediumFileName);
Other than that, the error message suggests that perhaps it is the omission of a file extension that is causing issues? Perhaps use Path.GetFileName(photo.FileName) or similar and use that as the end of your constructed pathname.

Play framework - uploading file in mySql

what is the simplest way to upload a file in mySql db in play 2.0 ?
Uploading files in the database or in a upload folder and then save a link in the database?
I would go for saving the reference in the database and uploading the image somewhere on your webserver. Or, if you persist on saving the image in the DB, save it as a thumb, this wil keep you database size maintainable and your db size acceptable. DBs are in my opinion for data and not assets like images.
Uploading files is documented: http://www.playframework.org/documentation/2.0/JavaFileUpload
How I did it:
View
In the view, make sure you have the correct enctype (this one is based on the twitter bootstrap)
#helper.form(controllers.orders.routes.Task.save, 'class -> "form-horizontal", 'enctype -> "multipart/form-data")
The file input:
#inputFile(taskForm("file1"), '_display -> "Attachment", '_label -> Messages("file"))
In your controller
// first i get the id of the task where I want to attach my files to
MultipartFormData body = request().body().asMultipartFormData();
List<FilePart> resourceFiles = body.getFiles();
Then iterate trough the attachments and upload them to the upload folder:
for (int i = 0; i < resourceFiles.size(); i++) {
FilePart picture = body.getFile(resourceFiles.get(i).getKey());
String fileName = picture.getFilename();
File file = picture.getFile();
File destinationFile = new File(play.Play.application().path().toString() + "//public//uploads//"
+ newTask.getCode() + "//" + i + "_" + fileName);
System.out.println(play.Play.application().path());
System.out.println(file.getAbsolutePath());
try {
FileUtils.copyFile(file, destinationFile);
TaskDocument taskDocument = new TaskDocument(newTask.description, "/assets/uploads/"
+ newTask.getCode() + "/" + i + "_" + fileName, loggedInUsr, newTask);
taskDocument.save();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Result
The code above result in creating a folder and placing the files in that folder. Example:
Folder: T000345
0_orange.png
1_apple.png
2_pear.png
EDIT : 2012-06-23
If you receive the error about the commons package you have to include this in the file Build.scala:
val appDependencies = Seq(
// Add your project dependencies here,
"mysql" % "mysql-connector-java" % "5.1.18",
"org.specs2" %% "specs2" % "1.9" % "test",
"commons-io" % "commons-io" % "2.2") // at least this one must be present!
Another way, you can store reference to photo in database.
In view:
<form action="#routes.Application.index" method="POST" enctype="multipart/form-data">
Photo<input type="file" name="photo"> <br>
<input type="submit" value="Submit">
</form>
In controller:
MultipartFormData body = request().body().asMultipartFormData();
FilePart photo = body.getFile("photo");
if (photo != null) {
String fileName = photo.getFilename();
File file = photo.getFile();
File newFile = new File(play.Play.application().path().toString() + "//public//uploads//"+ "_" + fileName);
file.renameTo(newFile); //here you are moving photo to new directory
System.out.println(newFile.getPath()); //this path you can store in database
}
}