Is there a way to get the full file path using a file browser and send that path as a String using Razor on MVC?I've been using a file selector but this only uploads the file name. Here's the code I have on my cshtml file:
#Html.TextBoxFor(m => m.IMG, new { type = "file" })
#Html.ValidationMessageFor(m => m.IMG)
But this methods only sends the name of the file as a string, not the full path.
For example instead of getting the path "C:\Users\UserMame\Pictures\Test.jpg", it only returns "Test.jpg"
You can do one thing. while saving the image,before saving add full path like
string rootpath = "~/Image/MyImages/";//change it according to your requirement
if (img != null)
{
if (!(Directory.Exists(Server.MapPath(rootpath))))
{
Directory.CreateDirectory(Server.MapPath(rootpath));//create a new directory if directory is doesn't exist in the root folder
}
string path = System.IO.Path.Combine(Server.MapPath(rootpath), "Test.jpg");
img.SaveAs(path);
}
you can use MapPath in the controller :
model.IMG=Server.MapPath("~/App_Data/"+Model.IMg);
and then pass the model to view
Related
I am doing some test with xamarin android. I have a text file in the asset folder, that I know how to access to this file:
using (Stream myFile= Assets.Open("myFile.txt"))
{
using (FileStream myDestinationFile= File.Create("myDestinationPath"))
{
myFile.CopyTo(myDestinationFile);
}
}
With this code, I can copy the file to another location, for example, "Personal", so I can edit the file because I know that I can't edit the files in the assets folder.
But I would like to pass the information of the text file directly to a string variable, beacause I don't need to edit the file, just to access to the information and pass this string as parameter of a method.
Is it possible to set a string variable with the information of the text file of the asset folder?
Thanks.
But I would like to pass the information of the text file directly to a string variable, beacause I don't need to edit the file, just to access to the information and pass this string as parameter of a method.
If you want to pass the string from the text file in Assect folder, you could use AssetManager.
Text file:
Set the Build Action to AndroidAssect:
Code:
// Create a new TextView and set it as our view
TextView tv = new TextView(this);
// Read the contents of our asset
string content;
AssetManager assets = this.Assets;
using (StreamReader sr = new StreamReader(assets.Open("TextFile1.txt")))
{
content = sr.ReadToEnd();
}
// Set TextView.Text to our asset content
tv.Text = content;
SetContentView(tv);
Result:
I want to delete a pdf file form my database as well as my public/uploads folder. It is deleting from the database but not from my public folder.
This is my controller:
public function deleteArticle($id) {
$article = Article::findOrFail($id);
File::delete($article->document);
$article->delete();
return redirect()->back();
}
/*This handles the posting of the file into the folder and storing of the url into the datab
$file = Input::file('document');
$file->move('uploads', $file->getClientOriginalName());
$document = asset('uploads/'.$file->getClientOriginalName());
$newArticle->document = $document;
As you are currently saving a url to the database ( by using the asset() function ) you can't delete the file by using that information.
It is usually enough to save just the document name in the database.
$document = $file->getClientOriginalName();
$newArticle->document = $document;
To delete the file you can then call:
File::delete(public_path('uploads/'.$article->document);
To Link to your file you can use the asset() method
asset('uploads/'.$article->document);
Storing the full URL in database is a bad idea. It will very hard to maintain files later. The best way is store only the filename with extension.
If you only have the filename in database, you can delete the file in this way:
$article = Article:findOrFail($id);
$document = $article->document; // take the image name from database
File::delete('uploads/'.$document); // delete the file
$article->delete() // delete the record from database
Edit
If you still want to use URL in database you can get the image name by using substr() and strpos() function. Example:
$image = substr($article->document,0,strpos("uploads/"));
You can get only the document name from URL and use it to delete the file.
To store only the filename follow this:
$document = $request->file('document')->getClientOriginalName();
I'm trying to upload file but get this error message :
move_uploaded_file() [<a href='function.move-uploaded-file'>function.move-uploaded-file</a>]: The second argument to copy() function cannot be a directory
I think there's something problem with this file but I've no idea to solve it..
<?php
class FileUploadController extends CController {
public function actionUpload() {
$model = new FileUpload();
$form = new CForm('application.views.fileUpload.uploadForm', $model);
if ($form->submitted('submit') && $form->validate()) {
$form->model->image = CUploadedFile::getInstance($form->model, 'image');
if($model->validate())
{
$model->image->saveAs('/opt/lampp/htdocs/upl/images');
Yii::app()->user->setFlash('success', 'File Uploaded');
$this->redirect(array('upload'));
}
}
$this->render('upload', array('form' => $form));
}
}
?>
You either need to check all files existed at '/opt/lampp/htdocs/upl/images' and check if the same named file is available or not, if available then just rename the file with extra "_1" every time, or you can always upload the file by renaming the file into some machine name sort of thing see the code below,
$name = rand(1000,9999) . time(); // rand(1000,9999) optional
$name = md5($name); //optional
$model->image->saveAs('/opt/lampp/htdocs/upl/images/' . $name . '.jpg');
This is what I usually do with file uploads, provided that you're saving the files references into the database or in any text file.
EDIT
Get Extension.
In case if you're required to get extension of the file rather then of hard-coded, you can use $model->image->getExtensionName(); it will get you the extension of the uploaded file without . (dot)
Finally, I solved it by myself:
The problem was located in line
$model->image->saveAs('/opt/lampp/htdocs/upl/images');
It should be :
$model->image->saveAs('/opt/lampp/htdocs/upl/images/images.jpg');
Now, there's another problem: when I upload 'new image', it will be replace the old file, I want the file(s) being uploaded not replaced the old file or I need something like rename as new file. Does anyone knows?
goto cuploadedfile.php .
over write this function with this
if($this->_error==UPLOAD_ERR_OK)
{
if($deleteTempFile)
return move_uploaded_file($this->_tempName,$file."/".$this->getName());
elseif(is_uploaded_file($this->_tempName))
return copy($this->_tempName, $file."/".$this->getName());
else
return false;
}
thank u.........
I have kept a word document (.docx) in one of the project folders which I want to use as a template.
This template contains custom header and footer lines for user. I want to facilitate user to download his own data in word format. For this, I want to write a function which will accept user data and referring the template it will create a new word file replacing the place-holders in the template and then return the new file for download (without saving it to server). That means the template needs to be intact as template.
Following is what I am trying. I was able to replace the placeholder. However, I am not aware of how to give the created content as downloadable file to user. I do not want to save the new content again in the server as another word file.
public void GenerateWord(string userData)
{
string templateDoc = HttpContext.Current.Server.MapPath("~/App_Data/Template.docx");
// Open the new Package
Package pkg = Package.Open(templateDoc, FileMode.Open, FileAccess.ReadWrite);
// Specify the URI of the part to be read
Uri uri = new Uri("/word/document.xml", UriKind.Relative);
PackagePart part = pkg.GetPart(uri);
XmlDocument xmlMainXMLDoc = new XmlDocument();
xmlMainXMLDoc.Load(part.GetStream(FileMode.Open, FileAccess.Read));
xmlMainXMLDoc.InnerXml = ReplacePlaceHoldersInTemplate(userData, xmlMainXMLDoc.InnerXml);
// Open the stream to write document
StreamWriter partWrt = new StreamWriter(part.GetStream(FileMode.Open, FileAccess.Write));
xmlMainXMLDoc.Save(partWrt);
partWrt.Flush();
partWrt.Close();
pkg.Close();
}
private string ReplacePlaceHoldersInTemplate(string toReplace, string templateBody)
{
templateBody = templateBody.Replace("#myPlaceHolder#", toReplace);
return templateBody;
}
I believe that the below line is saving the contents in the template file itself, which I don't want.
xmlMainXMLDoc.Save(partWrt);
How should I modify this code which can return the new content as downloadable word file to user?
I found the solution Here!
This code allows me to read the template file and modify it as I want and then to send response as downloadable attachment.
Here is the situation.
I have an action method, which returns a file, called "GetDocument" in "Documents" controller. It has one parameter of type Document, which contains document path, title, type etc.
I have a View for an entity, which has some documents attached with it. For example, a news story, with attached documents. On this view I show various links for the documents which the end user should be able to download.
The question is: How do I create such links which pass proper "Document" object to the "GetDocument" Action Method?
Edit: I do not want to show full path of the document to the user. In fact, I would like that I store documents in App_Data folder, so that they cannot be downloaded otherwise.
Thanks!
You could use an ActionLink:
#Html.ActionLink(
"Download",
"GetDocument",
new {
path = "report.pdf",
type = "application/pdf"
}
)
and then:
public ActionResult GetDocument(Document doc)
{
var appData = Server.MapPath("~/App_Data");
var file = Path.Combine(appData, doc.Path);
file = Path.GetFullPath(file);
if (!file.StartsWith(appData))
{
// Ensure there are no cheaters trying to read files
// outside of the App_Data folder like "../web.config"
throw new HttpException(403, "Forbidden");
}
if (!File.Exists(file))
{
return HttpNotFound();
}
return File(file, doc.Type, Path.GetFileName(file));
}
why would your controller need to know about the full document when the action is called? surely your documents have ids. take the id, ask your repository for the domain object, and then get the file.