How do I upload a file to an Acumatica Screen through HTTP virtual path? - asp.net

How do I upload a file to an Acumatica Screen through HTTP virtual path?
For example, I would like to upload mysite.com/files/abc.pdf to the Sales orders screen.

Below is a code snippet to achieve your goal.It is reading file from HTTP URL and attaching it to one of the existing Case.
//Graph for file management
PX.SM.UploadFileMaintenance filegraph = PXGraph.CreateInstance<PX.SM.UploadFileMaintenance>();
//Since you need file from HTTP URL - below is a sample
WebRequest request = WebRequest.Create("http://www.pdf995.com/samples/pdf.pdf");
using (System.IO.Stream dataStream = request.GetResponse().GetResponseStream())
{
using (System.IO.MemoryStream mStream = new System.IO.MemoryStream())
{
dataStream.CopyTo(mStream);
byte[] data = mStream.ToArray();
//Create file info, you may check different overloads as per your need
PX.SM.FileInfo fileinfo = new PX.SM.FileInfo("case.pdf", null, data);
if (filegraph.SaveFile(fileinfo))
{
if (fileinfo.UID.HasValue)
{
// To attach the file to case screen - example
CRCaseMaint graphCase = PXGraph.CreateInstance<CRCaseMaint>();
//Locate existing case
graphCase.Case.Current = graphCase.Case.Search<CRCase.caseCD>("<Case to which you want to attach file>");
//To Attach file
PXNoteAttribute.SetFileNotes(graphCase.Case.Cache, graphCase.Case.Current, fileinfo.UID.Value);
//To Attach note
PXNoteAttribute.SetNote(graphCase.Case.Cache, graphCase.Case.Current, "<Note you wish to specify>");
//Save case
graphCase.Save.Press();
}
}
}
}

Related

provider.FileData null in ReadAsMultipartAsync with media files

I am uploading files by using HTML File Upload control and passing data to ASP.NET Web API. Everything is working fine when I upload image or any text file or xml file. but it's giving error while I upload media files (mp3, mp4).
My code is,
string path = "//My path";
MultipartFormDataStreamProvider provider = new MultipartFormDataStreamProvider(path);
var task = Request.Content.ReadAsMultipartAsync(provider);
return await task.ContinueWith<bool>(t =>
{
string originalSavedAt = "";
foreach (MultipartFileData file in provider.FileData)
{
originalSavedAt = file.LocalFileName;
}
return true;
}, TaskScheduler.FromCurrentSynchronizationContext());
In above code, When I upload image file, it show me values in provider. FileData (provider.FileData.count is 1) in foreach loop.
But it is null (provider.FileData.count is 0) when I upload media file.
Status is failure in task lembda expression during media file upload, but status is RanToCompletion during image upload.
Do I need to add anything for media files. ?

ASP.NET Web API 2 file upload

I would like to know how best to handle file upload and addtional information added to the file to be uploaded using ASP.NET Web API 2 without MVC components. I have google the net and I can tell you I am more confused than I expected.
The Additional info will be stored in db and the file on the disk.
So far the Web API app I am building does not support multipart/form-data. It only supports the default media types. I know I need to create a media formatter.
Pls help.
I had wrote Javascript split File and upload to WEB API . i think you can reference my backend codes
In front-end you need using below code to upload your File
var xhr = new self.XMLHttpRequest();
xhr.open('POST', url, false);
xhr.setRequestHeader('Content-Type', 'application/octet-stream');
xhr.send(chunk);
In backend use Request.InputStream.Read to catch your file bytes
[HttpPost]
[ValidateInput(false)]
public string fileUpload(string filename)
{
byte[] file = new byte[Request.InputStream.Length];
Request.InputStream.Read(file, 0, Convert.ToInt32(Request.InputStream.Length));
BinaryWriter binWriter = new BinaryWriter(new MemoryStream());
binWriter.Write(file);
StreamReader reader = new StreamReader(binWriter.BaseStream);
reader.BaseStream.Position = 0;
//This example is recevied text file
while ((line = reader.ReadLine()) != null)
{
};
}
You can just serialize your file data into BASE64 and send them as a string in case of multipart/from-data is not allowed for some reason.

Cannot upload large (>50MB) files to SharePoint 2010 document library

I'm trying to upload a large file to a document library, but it fails after just a few seconds. The upload single document fails silently, upload multiple just shows a failed message. I've turned up the file size limit on the web application to 500MB, and the IIS request length to the same (from this blog), and increased the IIS timeout for good measure. Are there any other size caps that I've missed?
Update I've tried a few files of various sizes, anything 50MB or over fails, so I assume something somewhere is still set to the webapp default.
Update 2 Just tried uploading using the following powershell:
$web = Get-SPWeb http://{site address}
$folder = $web.GetFolder("Site Documents")
$file = Get-Item "C:\mydoc.txt" // ~ 150MB
$folder.Files.Add("SiteDocuments/mydoc.txt", $file.OpenRead(), $false)
and get this exception:
Exception calling "Add" with "3" argument(s): "<nativehr>0x80070003</nativehr><nativestack></nativestack>There is no file with URL 'http://{site address}/SiteDocuments/mydoc.txt' in this Web."
which strikes me as odd as of course the file wouldn't exist until it's been uploaded? N.B. while the document library has the name Site Documents, it has the URL SiteDocuments. Not sure why...
Are you sure you updated the right webapp? Is the filetype blocked by the server? Is there adequate space in your content database? I would check ULS logs after that and see if there is another error since it seems you hit the 3 spots you would need too update.
for uploading a large file, you can use the PUT method instead of using the other ways to upload a document.
by using a put method you will save the file into content database directly. see the example below
Note: the disadvantage of the code below is you cannot catch the object that is responsible for uploading directly, on other word, you cannot update the additional custom properties of the uploaded document directly.
public static bool UploadFileToDocumentLibrary(string sourceFilePath, string targetDocumentLibraryPath)
{
//Flag to indicate whether file was uploaded successfuly or not
bool isUploaded = true;
try
{
// Create a PUT Web request to upload the file.
WebRequest request = WebRequest.Create(targetDocumentLibraryPath);
//Set credentials of the current security context
request.Credentials = CredentialCache.DefaultCredentials;
request.Method = “PUT”;
// Create buffer to transfer file
byte[] fileBuffer = new byte[1024];
// Write the contents of the local file to the request stream.
using (Stream stream = request.GetRequestStream())
{
//Load the content from local file to stream
using (FileStream fsWorkbook = File.Open(sourceFilePath, FileMode.Open, FileAccess.Read))
{
//Get the start point
int startBuffer = fsWorkbook.Read(fileBuffer, 0, fileBuffer.Length);
for (int i = startBuffer; i > 0; i = fsWorkbook.Read(fileBuffer, 0, fileBuffer.Length))
{
stream.Write(fileBuffer, 0, i);
}
}
}
// Perform the PUT request
WebResponse response = request.GetResponse();
//Close response
response.Close();
}
catch (Exception ex)
{
//Set the flag to indiacte failure in uploading
isUploaded = false;
}
//Return the final upload status
return isUploaded;
}
and here are an example of calling this method
UploadFileToDocumentLibrary(#”C:\test.txt”, #”http://home-vs/Shared Documents/textfile.pdf”);

how to make a picture file downloadable?

I have an ASP.NET MVC3 application and I want to link_to an image file (png, jpeg, gif, etc), and when user clicks on it, the file goes to download, instead of the browser shows it; is there any way to do this?
take your link something like this:
#Html.ActionLink(
"Download Image", // text to show
"Download", // action name
["DownloadManager", // if need, controller]
new { filename = "my-image", fileext = "jpeg" } // file-name and extension
)
and action-method is here:
public FilePathResult Download(string filename, string fileext) {
var basePath = Server.MapPath("~/Contents/Images/");
var fullPath = System.IO.Path.Combine(
basePath, string.Concat(filename.Trim(), '.', fileext.Trim()));
var contentType = GetContentType(fileext);
// The file name to use in the file-download dialog box that is displayed in the browser.
var downloadName = "one-name-for-client-file." + fileext;
return File(fullPath, contentType, downloadName);
}
private string GetContentType(string fileext) {
switch (fileext) {
case "jpg":
case "jpe":
case "jpeg": return "image/jpeg";
case "png": return "image/x-png";
case "gif": return "image/gif";
default: throw new NotSupportedException();
}
}
UPDATE:
in fact, when a file is sending to a browser, this key/value will be generated in http-header:
Content-Disposition: attachment; filename=file-client-name.ext
which file-client-name.ext is the name.extension that you want the file save-as it on client system; for example, if you want to do this in ASP.NET (none mvc), you can create a HttpHandler, write the file-stream to Response, and just add the above key/value to the http-header:
Response.Headers.Add("Content-Disposition", "attachment; filename=" + "file-client-name.ext");
just this, enjoy :D
Well technically your browser is downloading it.
I don't think you can directly link to an image, and have the browser prompt to download.
You could try something where instead of linking directly to the image, you link to a page, which serves up the image in a zip file perhaps - which of course would prompt the download to occur.
Yes, you can.
Now, you'll need to customize this to suit your needs, but I created a FileController that returned files by an identifier (you can easily return by name).
public class FileController : Controller
{
public ActionResult Download(string name)
{
// check the existence of the filename, and load it in to memory
byte[] data = SomeFunctionToReadTheFile(name);
FileContentResult result = new FileContentResult(data, "image/jpg"); // or whatever it is
return result;
}
}
Now, how you read that file or where you get it from is up to you. I then created a route like this:
routes.MapRoute(null, "files/{name}", new { controller = "File", action = "Download"});
My database has a map of identifiers to files (it's actually more complex than this, but I am omitting that logic for brevity), I can write urls like:
"~/files/somefile"
And the relevant file is downloaded.
I don't think this is possible but a simple message saying right click to save image would suffice I think.

FileUpload problem with Struts on server

I am trying to create a upload servlet that handles enctype="multipart/form-data" from a form. The file I am trying to upload is a zip. However, I can upload and read the file on localhost, but when I upload to the server, I get a "File not found" error when I want to upload a file. Is this due to the Struts framework that I am using? Thanks for your help. Here is part of my code, I am using FileUpload from http://commons.apache.org/fileupload/using.html
I have changed to using ZipInputStream, however, how to I reference to the ZipFile zip without using a local disk address (ie: C://zipfile.zip). zip is null because its not instantiated. I will need to unzip and read the zipentry in memory, without writing to the server.
For the upload servlet:
>
private ZipFile zip;
private CSVReader reader;
boolean isMultipart = ServletFileUpload.isMultipartContent(request);
if(isMultipart){
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List <FileItem> items = upload.parseRequest(request);
Iterator iter = items.iterator();
while (iter.hasNext()) {
//Iterating through the uploaded zip file and reading the content
FileItem item = (FileItem) iter.next();
ZipInputStream input = new ZipInputStream(item.getInputStream());
ZipEntry entry = null;
while (( entry= input.getNextEntry()) != null) {
ZipEntry entry = (ZipEntry) e.nextElement();
if(entry.getName().toString().equals("file.csv")){
//unzip(entry)
}
}
}
public static void unzip(ZipEntry entry){
try{
InputStream inputStream = **zip**.getInputStream(entry);
InputStreamReader inputStreamReader = new InputStreamReader(inputStream);
reader = new CSVReader(inputStreamReader);
}
catch(Exception e){
e.printStackTrace();
}
}
<
Here,
zip = new ZipFile(new File(fileName));
You're assuming that the local disk file system at the server machine already contains the file with exactly the same name as it is at the client side. This is a wrong assumption. That it worked at localhost is obviously because both the webbrowser and webserver "by coincidence" runs at physically the same machine with the same disk file system.
Also, you seem to be using Internet Explorer as browser which incorrectly includes the full path in the filename like C:/full/path/to/file.ext. You shouldn't be relying on this browser specific bug. Other browsers like Firefox correctly sends only the file name like file.ext, which in turn would have caused a failure with new File(fileName) (which should have helped you to spot your mistake much sooner).
To fix this "problem", you need to obtain the file contents as InputStream by item.getInputStream():
ZipInputStream input = new ZipInputStream(item.getInputStream());
// ...
Or to write it to disk by item.write(file) and reference it in ZipFile:
File file = File.createTempFile("temp", ".zip");
item.write(file);
ZipFile zipFile = new ZipFile(file);
// ...
Note: don't forget to check the file extension beforehand, else this may choke.

Resources