Front end base64/blob asset upload via form submission in CraftCMS3 - craftcms

Goal
I only have baes64/blob data available from a <canvas /> and want to upload the image via from submission in front-end.
Methods I've tried
I've read about Uploading Files from Front-End Entry Forms in doc.
CraftCMS ONLY supports <input type="file">. The file type input does not support accepting re-assign value like other input tags directly.

Assets fields do actually support submitting Base64-encoded data; it just wasn’t documented. Done now though!

The file type input now support reassign value.
Steps:
convert your blob into file obj
Update your Filelist in js.
Updated Filelist replace with your input files.
let file = new File([blob], fileName);
let list = new DataTransfer();
list.items.add(file);
$(input)[0].files = myFileList;
Here is original thread

Related

File object from URL

I'd like to create a file object from an image located at a specific url. I'm downloading the file with Net Http:
img = Net::HTTP.get_response(URI.parse('https://prium-solutions.com/wp-content/uploads/2016/11/rails-1.png'))
file = File.read(img.body)
However, I get ArgumentError: string contains null byte when trying to read the file and store in into the file variable.
How can I do this without having to store it locally ?
Since File deals with reading from storage, it's really not applicable here. The read method is expecting you to hand it a location to read from, and you're passing in binary data.
If you have a situation where you need to interface with a library that expects an object that is streaming, you can wrap the string body in a StringIO object:
file = StringIO.new(img)
# you can now call file.read, file.seek, file.rewind, etc.

TCPDF generated PDF to automatically display in Acrobat Reader

I am able to use TCPDF and generate a PDF in the browser using JQuery/JavaScript:
window.open("", "pdfWindow",scrollbars=yes, resizable=yes, top=500, left=500, width=400, height=400");
$("#" + formID).attr('action','tcpdf/example/genReport.pdf').attr('target','pdfWindow');
In genReport.pdf, I am using $pdf->Output('genReport.pdf', 'I');
When genReport.pdf is generated, it appears in a new tab with the standard browser settings. I wanted to know if there is a way to have the generated PDF automatically display in Acrobat Reader?
Any help will be greatly appreciated.
According to the documentation of the output() function, the second parameter can be one of those:
I: send the file inline to the browser (default). The plug-in is used if available. The name given by name is used when one selects
the "Save as" option on the link generating the PDF.
D: send to the browser and force a file download with the name given by name.
F: save to a local server file with the name given by name.
S: return the document as a string (name is ignored).
FI: equivalent to F + I option
FD: equivalent to F + D option
E: return the document as base64 mime multi-part email attachment (RFC 2045)
So I'd suggest using $pdf->Output('genReport.pdf', 'D'); this will open the download dialog and the user can choose to either open or download the file.

Multiple input file tags with IOS 6+ on iPad/iPhone

EDIT :
I've been able to resolve this, after finding that iOS uploads every image as "image.jpg". In freeASPUpload.asp, I changed the following :
For Each fileItem In UploadedFiles.Items
filePath = path & fileItem.FileName
Set streamFile = Server.CreateObject("ADODB.Stream")
streamFile.Type = adTypeBinary
streamFile.Open
StreamRequest.Position=fileItem.Start
StreamRequest.CopyTo streamFile, fileItem.Length
streamFile.SaveToFile path & FileName, adSaveCreateOverWrite
streamFile.close
Set streamFile = Nothing
fileItem.Path = filePath
Next
To :
For Each fileItem In UploadedFiles.Items
FileName = GetFileName(path, fileItem.FileName)
fileItem.FileName = FileName
filePath = path & fileItem.FileName
Set streamFile = Server.CreateObject("ADODB.Stream")
streamFile.Type = adTypeBinary
streamFile.Open
StreamRequest.Position=fileItem.Start
StreamRequest.CopyTo streamFile, fileItem.Length
streamFile.SaveToFile path & FileName, adSaveCreateOverWrite
streamFile.close
Set streamFile = Nothing
fileItem.Path = filePath
Next
This is within the save function of the script. The GetFileName function iterates over what is in the folder already, and adds a number until it is unique. It then updates the file key to its new name. I've left an "image.jpg" file in the temp folder, so that it always finds one. That works for now.
What I've found, however, is for some reason, it flips the second photo out of the five that the form allows for..
I will try to fix that / look for others with the same issue. I've always had problems with iPhones and iPads rotating pictures, and it's never consistent.
I'm trying to grab multiple files from a mobile fleet of iPads and iPhones. Currently I have 5
<input type="file" name="fileX" accept="image/*">
This works fine in a browser (using free asp upload / classic ASP). In testing, it works with IOS, but only if I send one file. If I send more then one via the form, I get the error 'file not found'. It seems like the files aren't being sent at all.
The file not found kicks back when trying to manipulate the file via FSO.
Uploads here :
Dim Upload, fileName, fileSize, ks, i, fileKey
Set Upload = New FreeASPUpload
SaveFiles = ""
uploadsDirVar = "directory"
Upload.Save(uploadsDirVar)
ks = Upload.UploadedFiles.keys
Errors out here :
Set f=fs.GetFile(uploadsDirVar & "\" & Upload.UploadedFiles(fileKey).FileName)
Any ideas on how I can get around this? Everything I've read points towards the HTML5 multiple tag on a single input. However, in my scenario, this won't work. I'm also tying descriptions for the images to the fields based on field name, restricting the upload to 5, re-sizing the images on the action page before passing it to its final destination and attaching them to an email.
Any advice welcome, and thank you for your time!
**Edit
The issue seems to be that IOS names all uploads "image", coming from either the camera or the library. Now the problem is how to rename the image before the script attempts to upload it. From what I'm understanding, it needs to happen within the asp upload component before it places the file.
See the above edit for the answer. As for the flipped images - turns out they are flipped straight from the iPad. I checked the exif data and I'm not sure how to account for this in my system. If I find the answer, I'll post here.

Struts File Upload identify correct extension instead of .tmp

I am new to Struts and working on File Upload using Struts.
Client:
It is Java Program which hits my Strut app by using apache HttpClient API and provides me
File.
Client as per need sometime gives me .wav file and sometime .zip file and sometime both.
Server:
Struts app which got the request from client app and upload the file.
Here, problem comes as I upload the file, it get uploaded using ".tmp" extension, which I want to get uploaded with the same extension what client has passed.
Or there is any other way by which we can check what is the extension of the file client has sent....?
I am stuck in this problem and not able to go ahead.
Please Find the code attached and tell me what modification I have to do:
Server Code:
MultiPartRequestWrapper multiWrapper=null;
File baseFile=null;
System.out.println("inside do post");
multiWrapper = ((MultiPartRequestWrapper)request);
Enumeration e = multiWrapper.getFileParameterNames();
while (e.hasMoreElements()) {
// get the value of this input tag
String inputValue = (String) e.nextElement();
// Get a File object for the uploaded File
File[] file = multiWrapper.getFiles(inputValue);
// If it's null the upload failed
if (file != null) {
FileInputStream fis=new FileInputStream(file[0]);
System.out.println(file[0].getAbsolutePath());
System.out.println(fis);
int ch;
while((ch=fis.read())!=-1){
System.out.print((char)ch);
}
}
}
System.out.println("III :"+multiWrapper.getParameter("method"));
Client code:
HttpClient client = new HttpClient();
MultipartPostMethod mPost = new MultipartPostMethod(url);
File zipFile = new File("D:\\a.zip");
File wavFile = new File("D:\\b.wav");
mPost.addParameter("recipientFile", zipFile);
mPost.addParameter("promptFile", wavFile);
mPost.addParameter("method", "addCampaign");
statusCode1 = client.executeMethod(mPost);
actually Client is written long back and cant be modified and I want to identify something at server side only to find the extension.
Please help, Thanks.
Struts2 File Uploader interceptor when uploading file pass the content type information to the Action class and one can easily find the file type by comparing contentType with MIME type.
If you want to can create a map with key as content type and file type as its value like
map.Add("image/bmp",".bmp", )
map.Add("image/gif",".gif", )
map.Add("image/jpeg",".jpeg", )
and can easily fetch the type based on the extension provides.Hope this will help you.

Open XML SDK: opening a Word template and saving to a different file-name

This one very simple thing I can't find the right technique. What I want is to open a .dotx template, make some changes and save as the same name but .docx extension. I can save a WordprocessingDocument but only to the place it's loaded from. I've tried manually constructing a new document using the WordprocessingDocument with changes made but nothing's worked so far, I tried MainDocumentPart.Document.WriteTo(XmlWriter.Create(targetPath)); and just got an empty file.
What's the right way here? Is a .dotx file special at all or just another document as far as the SDK is concerned - should i simply copy the template to the destination and then open that and make changes, and save? I did have some concerns if my app is called from two clients at once, if it can open the same .dotx file twice... in this case creating a copy would be sensible anyway... but for my own curiosity I still want to know how to do "Save As".
I would suggest just using File.IO to copy the dotx file to a docx file and make your changes there, if that works for your situation. There's also a ChangeDocumentType function you'll have to call to prevent an error in the new docx file.
File.Copy(#"\path\to\template.dotx", #"\path\to\template.docx");
using(WordprocessingDocument newdoc = WordprocessingDocument.Open(#"\path\to\template.docx", true))
{
newdoc.ChangeDocumentType(WordprocessingDocumentType.Document);
//manipulate document....
}
While M_R_H's answer is correct, there is a faster, less IO-intensive method:
Read the template or document into a MemoryStream.
Within a using statement:
open the template or document on the MemoryStream.
If you opened a template (.dotx) and you want to store it as a document (.docx), you must change the document type to WordprocessingDocumentType.Document. Otherwise, Word will complain when you try to open the document.
Manipulate your document.
Write the contents of the MemoryStream to a file.
For the first step, we can use the following method, which reads a file into a MemoryStream:
public static MemoryStream ReadAllBytesToMemoryStream(string path)
{
byte[] buffer = File.ReadAllBytes(path);
var destStream = new MemoryStream(buffer.Length);
destStream.Write(buffer, 0, buffer.Length);
destStream.Seek(0, SeekOrigin.Begin);
return destStream;
}
Then, we can use that in the following way (replicating as much of M_R_H's code as possible):
// Step #1 (note the using declaration)
using MemoryStream stream = ReadAllBytesToMemoryStream(#"\path\to\template.dotx");
// Step #2
using (WordprocessingDocument newdoc = WordprocessingDocument.Open(stream, true)
{
// You must do the following to turn a template into a document.
newdoc.ChangeDocumentType(WordprocessingDocumentType.Document);
// Manipulate document (completely in memory now) ...
}
// Step #3
File.WriteAllBytes(#"\path\to\template.docx", stream.GetBuffer());
See this post for a comparison of methods for cloning (or duplicating) Word documents or templates.

Resources