I need a controller to handle file uploads. Is it possible to just have a handler print text directly to the page rather than return view(); ?
public ActionResult Upload(HttpContext context)
{
HttpPostedFile file = context.Request.Files["fileData"];
Guid userGuid = (Guid)Membership.GetUser().ProviderUserKey;
string userID = userGuid.ToString();
string targetLocation = "D:\\inetpub\\wwwroot\\RTDOTNETMEMBER\\audio\\songs\\mp3\\" + userID + "\\" + file.FileName;
file.SaveAs(targetLocation);
Response.Write("Testing");
}
Perhaps using ContentResult will do the job:
return new ContentResult() {
Content = "Testing",
ContentEncoding = System.Text.Encoding.UTF32,
ContentType = "text/plain"
};
Just change the return type of your action method to string and return a string. It would look somethig like this:
public string ReturnString()
{
return "Just a string";
}
Related
I want to do this with c# asp.net, can you tell me the actual methods I need to use to handle this part: {get file from filesystem}?
ActionResult FunctionToServeFile(fileName, guid)
{
File result;
var itemEntry = db.items.firstOrDefault(x => x.guid == guid);
var itemPermissionsEntry = itemEntry.userPermissions
.firstOrDefault(x => x.user == user.identity.name);
if(itemPermissionsEntry.view == true || itemPermissionsEntry.Modify == true)
{
result = {get file from filesystem}
return result;
}
else
{
return error;
}
}
There is direct support for this with FileResult, and Controller has a set of helpers:
In your action:
return File(filename, contentType);
This is the solution I arrived at:
public ActionResult DownloadFile(string fileName, Guid guid)
{
Item item = db.Items.FirstOrDefault(x => x.ItemGUID == guid);
if (item == null)
return null;
List <SecurityMask> accessList = GetAccessRightsForItem(item.item_id,
ActiveDirectory.GetUserSID(User.Identity.Name));
bool hasAccess = false || (accessList.Contains(SecurityMask.View) || accessList.Contains(SecurityMask.Modify));
string filePath = Path.GetFullPath(Path.Combine(HttpRuntime.AppDomainAppPath,
"Files\\Items", guid.ToString(), fileName));
string mimeType = MimeMapping.GetMimeMapping(filePath);
bool fileExists = System.IO.File.Exists(filePath);
if (hasAccess && fileExists)
{
return File(System.IO.File.ReadAllBytes(filePath), mimeType);
}
return null;
}
You have to have the file somewhere in your server, so just make a method to get that path and serve it through the controller like this :
string thefile = SomeModelClass.SomeMethod(fileName, guid); // get full path to the file
var cd = new System.Net.Mime.ContentDisposition
{
FileName = Path.GetFileName(thefile),
Inline = false
};
Response.AppendHeader("Content-Disposition", cd.ToString());
string fileext = Path.GetExtension(thefile);
string mimeType = SomeMetodToMapextensionToMimeType(fileext); // You have to implement this by yourself
return File(System.IO.File.ReadAllBytes(thefile), mime);
I have to send the files along with some description about those to the server.
So as per above image, I want to upload a file and provide the description of file in a text box on right side of it. After clicking select files link, the user can select another file to upload and it will also have description text box. After clicking upload files, along with the file, description of it neet to upload to the server.
I am using plupload to do it. But it is just uploading file and not description.
Also, I am using MVC. So please suggest any solution to it or suggest any other javascript library which can fulfill my requirements.
Below is the MVC code,
public string Upload(List<HttpPostedFileBase> fileUploads,List<string> fileDescription)
{
int count = 0;
foreach (HttpPostedFileBase file in fileUploads)
{
byte[] fileData = new byte[file.ContentLength];
file.InputStream.Read(fileData, 0, file.ContentLength);
db.UploadedFiles.AddObject(new UploadedFile
{
FileDescription = fileDescription[count],
FileBinary = fileData,
FileName = file.FileName
});
count++;
}
db.SaveChanges();
return "Success";
}
Below is javascript code
var uploadFiles = [];
var descs = [];
var count = 0;
plupload.each(uploader.files, function (file) {
var id = file.id;
var fileUpload = file;
uploadFiles[count] = file;
descs[count] = $("#" + id + "_desc").val();
count++;
});
var da = { fileDescription: descs,fileUploads: uploader.files };
$.ajax({
url: '/LumosQC/Upload',
data: da,
method: 'POST',
}).done(function (data1) {
alert("Success");
}).error(function (a, b, c) {
console.log(a);
});
You can modify the route you use for uploading and use something like
...
[Route("upload/{description}")]
public HttpResponseMessage Upload(string description)
...
Or you can put description into cookie (but I would recomend to use the first approach it's cleaner)
function createCookie(name,value,days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days*24*60*60*1000));
expires = "; expires=" + date.toUTCString();
}
document.cookie = name + "=" + value + expires + "; path=/";
}
createCookie('desciption', 'your description', 1)
and then
Request.Cookies["description"]
UPDATE
Now I see you need to upload multiple files, for that you can use the same approach with modified route
[Route("upload")]
public string Upload(List<HttpPostedFileBase> fileUploads, [FromUri] string[] fileDescription)
Create view model and use as parameter in action method,
ViewModel :
public class UploadViewModel
{
public List<string> FileDescriptions;
public List<HttpPostedFileBase> Files;
}
Action method :
public string Upload(UploadViewModel model)
{
// ....
}
that will bind the data correctly.
How do I post a httppostedfile to a webapi?
Basically I want the user to select an excel file and I want to post it to my webapi.
The gui is made with classic asp.net and the webapi is made with new .NET apicontroller.
I have done some api coding before but then I used JSON and that doesn't seem to work very good with this kind of object.
Can someone please just point me in the right direction so that I can continue to search for info. Right now I don't even know what to search for.
I solved this by doing this:
In my controller:
using (var client = new HttpClient())
using (var content = new MultipartFormDataContent())
{
client.BaseAddress = new Uri(System.Configuration.ConfigurationManager.AppSettings["PAM_WebApi"]);
var fileContent = new ByteArrayContent(excelBytes);
fileContent.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = fileName
};
content.Add(fileContent);
var result = client.PostAsync("api/Product", content).Result;
}
And here is my ApiController:
[RoutePrefix("api/Product")]
public class ProductController : ApiController
{
public async Task<List<string>> PostAsync()
{
if (Request.Content.IsMimeMultipartContent())
{
string uploadPath = HttpContext.Current.Server.MapPath("~/uploads");
if (!System.IO.Directory.Exists(uploadPath))
{
System.IO.Directory.CreateDirectory(uploadPath);
}
MyStreamProvider streamProvider = new MyStreamProvider(uploadPath);
await Request.Content.ReadAsMultipartAsync(streamProvider);
List<string> messages = new List<string>();
foreach (var file in streamProvider.FileData)
{
FileInfo fi = new FileInfo(file.LocalFileName);
messages.Add("File uploaded as " + fi.FullName + " (" + fi.Length + " bytes)");
}
return messages;
}
else
{
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.BadRequest, "Invalid Request!");
throw new HttpResponseException(response);
}
}
}
public class MyStreamProvider : MultipartFormDataStreamProvider
{
public MyStreamProvider(string uploadPath)
: base(uploadPath)
{
}
public override string GetLocalFileName(HttpContentHeaders headers)
{
string fileName = headers.ContentDisposition.FileName;
if (string.IsNullOrWhiteSpace(fileName))
{
fileName = Guid.NewGuid().ToString() + ".xls";
}
return fileName.Replace("\"", string.Empty);
}
}
I found this code in a tutorial so i'm not the one to be credited.
So here i write the file to a folder. And because of the mysreamprovider i can get the same name of the file as the file i first added in the GUI. I also add the ending ".xls" to the file because my program is only going to handle excel files. Therefor i have added some validation to the input in my GUI to so that i know that the file added is an excel file.
I have the following Kendo upload control
#(Html.Kendo().Upload()
.Name("files")
.Async(a => a
.Save("SaveBackgroundImage", "Plans")
.AutoUpload(true))
.Multiple(false)
.Events(events => events.Success("onSuccess")))
My controller:
public ActionResult SaveBackgroundImage(IEnumerable<HttpPostedFileBase> floorplanFiles, string floorplanId)
{
foreach (var file in files)
{
string fileName = "ABC.jpg" //this will be random
var physicalPath = Path.Combine(Server.MapPath("~/Images/Floorplans/Fullsize"), fileName);
file.SaveAs(physicalPath);
}
// Return an empty string to signify success
return Content("");
}
My javascript:
function onSuccess(e) {
var filename = getFileInfo(e);
alert(filename);
}
function getFileInfo(e) {
return $.map(e.files, function (file) {
var info = file.name;
return info;
}).join(", ");
}
How do I get back "ABC.jpg" as my filename in my javascript instead of the original filename that I select to upload?
Solved by doing this in my controller:
var newImageName = "123.jpg";
return Json(new { ImageName = newImageName }, "text/plain");
and in the onSuccess function:
function onSuccess(e) {
var imageName = e.response.ImageName;
}
I have two actions and I want to send HttpPostedFile from first action to another action using session or tempdata. who can help realize it this is my code, exeption in xdocument load - IIs Express/*.xml don't found
[HttpPost]
public ActionResult Index(HttpPostedFileBase fil)
{
if (fil != null && fil.ContentLength > 0)
{
Session["doc2"] = fil;
}
return RedirectToAction("Xmlview");
}
[HttpGet]
public ActionResult Xmlview()
{
HttpPostedFileBase file2= Session["doc2"] as HttpPostedFileBase;
var fileex = Path.GetExtension(file2.FileName);
var fileName = Path.GetFullPath(file2.FileName);
string xmlstr = ".xml";
Value model2 = new Value();
string strall = "";
if (fileex.Contains(xmlstr))
{
XDocument xml = XDocument.Load(fileName); // exeption hear IIs Express/*.xml don't found
var allElements = xml.Elements();
}
Try this. Hope it will work. I din't gave a try.
[HttpPost]
public ActionResult Index(HttpPostedFileBase fil)
{
if (fil != null && fil.ContentLength > 0)
{
// Read bytes from http input stream
BinaryReader b = new BinaryReader(file.InputStream);
byte[] binData = b.ReadBytes(file.InputStream.Length);
string result = System.Text.Encoding.UTF8.GetString(binData);
Session["doc2"] = result;
}
return RedirectToAction("Xmlview");
}
[HttpGet]
public ActionResult Xmlview()
{
Value model2 = new Value();
string strall = "";
string content = Session["doc2"].ToString();
if (!String.IsNullOrEmpty(content))
{
XDocument xml = XDocument.Parse(content);
var allElements = xml.Elements();
}
}