Anybody knows how to upload a file and save it into a database. And it can be viewed in a .jsp page. When the user clicks on it, the user can download it and/or if it is a .doc file (like MS Word .doc, .docx files) it can be viewed online like how facebook implements it.
I am a very very new to uploading files. Please be patient with me. What only I knew is this:
<form>
<input type="file"/>
<input type="submit" value="Upload"/>
</form>
And also, how to limit the file size, and limit only a group of file type like upload only .txt,.doc,.pdf etc files.
From the File Upload Interceptor documentation:
Parameters
maximumSize (optional) - the maximum size (in bytes) that the interceptor will allow a file reference to be set on the action. Note, this is not related to the various properties found in struts.properties. Default to approximately 2MB.
allowedTypes (optional) - a comma separated list of content types (ie: text/html) that the interceptor will allow a file reference to be set on the action. If none is specified allow all types to be uploaded.
allowedExtensions (optional) - a comma separated list of file extensions (ie: .html) that the interceptor will allow a file reference to be set on the action. If none is specified allow all extensions to be uploaded.
For example, to block all files except png, gif and jpeg under 10 MegaBytes:
<interceptor-ref name="fileUpload">
<param name="maximumSize">
10485760
</param>
<param name="allowedTypes">
image/png,image/gif,image/jpeg
</param>
</interceptor-ref>
Read more on File size limit and overall Multipart request size limit.
Be sure to check out the official Struts2 File Upload page too for a complete overview of the subject.
Related
I have an MHT (Microsoft web archive) file that I have added to my project folder. I need this file to display in a WebView on a help page. I have set the file's build action to "Content," like this question reccomended. I then use this code in the page's Loaded event handler.
Try
Dim strHelpNavigate = Path.Combine(Windows.ApplicationModel.Package.Current.InstalledLocation.ToString(), "\MyAppsHelp.mht")
webHelp.Navigate(New Uri(strHelpNavigate))
Catch ex As Exception
webHelp.NavigateToString("<html><head><style>body {font-family: segoe ui; color: white; background-color: black;}</style></head><body><h2>Sorry, the help page is currently unavailable.</h2></body></html>")
End Try
This code produces an exception: {"Invalid URI: The format of the URI could not be determined."}
I have also tried passing "\MyAppsHelp.mht" to the Navigate method like this question reccomended, but this produces the same exception, and I see from the Local window that the string passed to the Navigate method is the same either way.
Does anyone have any advice on how to display this file in the WebView?
WebView does not natively support HTML archive files, but you can do the work convert these files to html + images if you're so inclined.
Open the .mht file in notepad, and you'll see that there are separate sections for each part of the HTML file - you can parse these sections to get the HTML out, then the base64 encoded images, then save them in your local app folder and use WebView.NavigateToLocalStreamUri to load them. See http://blogs.msdn.com/b/wsdevsol/archive/2014/06/20/a-primer-on-webview-navigatetolocalstreamuri.aspx for details on how to use this method.
OF course, if it's a static file that you will be using all of the time, it would be far easier to just convert it before packaging the app.
My app allows for a text file to be emailed to other users with or without images and audio. When there's no images or audio, then the app sends the text file "as is" with a custom extension (e.g. text.xxx). When there's audio and images, the app zips the text file along with the images and audio into a file named something like text.xxx.zip.
Prior to iOS 6 this worked fine. Pre iOS 6, the app was given the URL of the text.xxx.zip file. Now, with iOS 6, it appears that the file is already unzipped by Mail, and only the text.xxx is sent to the openURL handler.
Does anyone out there have any experience with this? Suggestions for a better approach? I'm thinking I'll need to come up with a unique extension for the zipped case...
So after pounding my head on this for the last 24 hours or so, this is what "solves" the problem:
1) Change any existing attachment filenames from test.xxx.zip to test.zip. It looks iOS6 Mail is assuming that anything of the form filename.xxx.zip, is really just a compressed version of filename.xxx. (Maybe that's a standard somewhere?) Also noted that if I changed the filename to test.yyy.zip it then said it couldn't open the attachment. (presumably since no one registered for the ".yyy" extension).
2) Rewrite code to not use .zip extension in the future to prevent similar issues.
I also discovered that for multiple document types (e.g., .xxx, .zzz) you must specify a different mime type for each in the UTI declaration - otherwise Mail appends the first UTI extension it finds to the object and then calls openURL. So, in other words, if you're set up to handle a flat file (.xxx) and a zip file (.zzz), but you use the same mime type (e.g. application/myappname) and "xxx" is defined first, when openURL is called for your file "test.zzz", it will actually pass it to openURL as "test.xxx".
I have a form with a file input:
<input type="file" id="uploadFile" name="uploadFile" />
I submit the form using the ajaxForm method of the JQuery form plugin.
Then, in the code to handle the post, I read and process the file. I use cfspreadsheet to read the file directly from the file input field:
<cfspreadsheet
action="read"
src="#form.uploadFile#"
sheet="1"
query="spreadsheetData"
headerRow="1"
excludeHeaderRow="true"
>
This all works correctly.
I decided that I want to email the spreadsheet to the administrator as well. I thought I could accomplish this simply with a cfmail tag that includes the following cfmailparam tag:
<cfmail to="myEmailAddress#email.com"
from="fromEmail#email.com"
subject="Upload File" type="HTML">
<cfmailparam file="#form.uploadFile#" />
File processed successfully
</cfmail>
However, this is not working correctly - the email is not sent. What am I doing wrong?
Leigh's solution works well and you have probably already implemented in your code. I thought I'd put my 0.02 cents in about why this is a problem to begin with.
When you upload a file the file is placed in a temp folder location. If you do nothing with the file to put it in a final destination the file is deleted - probably at the end of your request.
Meanwhile the cfmailparam does not actually attach the file at runtime. It leaves it to the spooler process to do that. If you take a look in your ColdFusion installs "mail/spool" directory you will see a file with .cfmail extension. If you can't "catch" one before delivery check your undeliverable folder - there's bound to be a few hanging around in there.
The .cfmail file serves as an instruction to the spooler service which sends the mail. It has a subject, from, to, server address, body etc.
If you attach a file you will see something at the bottom of this file that looks like this:
file: D:\jrun\temp\blah.tmp
file-type: application/octet-stream; name="I am the file you uploaded.tmp"
file-disposition: attachment
remove: false
At runtime CF grabs this file and does what Leigh is suggesting - places it as binary with a mailpart (base64 encoded) into the main body of the message. So what is happening is that by the time the spooler service gets around to attempting to open and attach this file the file is long gone because the request has ended. I also think that the file exists with a ".tmp" extension in this temporary directory - which is obviously not what you want to attach (but that could be a previous version of CF).
To fix it, first use cffile with the "upload" action to put the file in a real (instead of temporary) folder on the disk. Then use cfmailparam to attach the file. NOTE: The "remove" attribute set to yes will cause CF to delete the file once it has successfully sent the mail - which is the effect I believe you are looking for.
I've implemented an upload utility using Struts2. I'm already restricting uploading a specific file type by programatically checking in my setFileContentType() method in my action class.
One remaining issue is to display to the user a customized error page in case the uploaded file exceeds the max file size setting.
I've researched this and saw how the validation interceptor should be used along with the returned "input" result. However, i still can't put all the pieces together.
My end goal is the following: If the user attempts to upload a large file, i want to display a new page with my own error message.
Any tips/suggestions?
UPDATE
I have the following configuration in my struts.xml:
<action name="FileUpload" class="common.FileUpload">
<interceptor-ref name="fileUpload"/>
<result name="success">common/FileUpload/FileUpload.jsp</result>
<result name="UploadResult">common/FileUpload/FileUploadResult.jsp</result>
</action>
I know the above configuration is missing the validation interceptor in case i want to detect the file size error. The problem is that i'm not sure how that comes into play at this point.
Thanks
FileUpload has a filesize parameter, you can use that in your configuration
<interceptor-ref name="fileUpload">
<param name="maximumSize">50</param>
</interceptor-ref>
If you want to provide custom message you can set here
struts.messages.error.file.too.large
Occurs when the uploaded file is too large as specified by
maximumSize.
Make Your action ValidationAware and you will be notified if Struts2 encounters this error, your addFieldError will be invoked to notify you of the error where key will struts.messages.error.file.too.large and message that you have defined in properties file, once your addFieldError is invoked you can take necessary action.
FileUploadInterceptor while uploading files will also run validation on the file or file type, size and if action implements ValidationAware then it will set validation message in that action by calling addFieldError callback method
Is there any other way that I can just check the size of a file before upload? The requirement is if the file exceeded the limit, the form mustn't submit. If it's not, I have to do the ordinary upload using the form and I don't have to exactly upload the file to the server using Flash.
Is there any other way that I can just check the size of a file before upload?
Not in JavaScript, the file size is not in the DOM.
when instantiating SWFUpload, there are two parameters you need to pass: file_size_limit, and file_queue_error_handler:
new SWFUpload({
file_size_limit: "10 MB",
file_queue_error_handler: queueErrorHandler,
[...]
})
and then:
function queueErrorHandler(file, errorCode) {
if (errorCode == SWFUpload.QUEUE_ERROR.FILE_EXCEEDS_SIZE_LIMIT) {
alert("File exceeds the 10MB limit!");
}
}
this checks if the file size is within limits before starting the upload
with the W3C FileAPI (implemented at least by Firefox 3.6) you can.
See this link for details
http://hacks.mozilla.org/2009/12/w3c-fileapi-in-firefox-3-6/
Cheers
Checking the file size through the SWFUpload control is possible. Just put the SWFUpload control outside of the Web form tags. Tell the user click on the SWFUpload button and point to his upload file. Use javascript to determine the file size, then utilize this information as you see fit such as populating a validation function. Then your main form will need to ask the user to point to their upload file again, and it is this field which will do the actual uploading of the file. When the form is submitted, the SWFUpload control will be completely ignored since it's not part of the main form.