File Upload - code improvement help
I have asked similar kind of question before, but it was termed as meaningless. I hope this time it will have some meaning(I am now following the instructions :)).
I got this code from online, the address is mentioned in the comments. With little changes it is serving the purpose well. However, the upload time is a bit high and I was wondering is there a way to improve that.
<!-- upload.jsp -->
<!-- http://forums.codecharge.com/posts.php?post_id=44078 -->
<html>
<head>
<title>Upload Page</title>
<jsp:useBean class = "formjavabean.application" id = "applicationId" scope = "session" />
</head>
<body>
<%@ page import="java.io.*" %>
<%
String userEmail = applicationId.getUserEmail() ;
File user = new File("C:\\JBoss\\jboss-4.0.5.GA\\bin\\Fastran\\" + userEmail ) ;
user.mkdir() ;
String contentType = request.getContentType();
System.out.println("Content type is :: " +contentType);
if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0))
DataInputStream in = new DataInputStream(request.getInputStream());
int formDataLength = request.getContentLength();
byte dataBytes[] = new byte[formDataLength];
int byteRead = 0;
int totalBytesRead = 0;
while (totalBytesRead < formDataLength)
byteRead = in.read(dataBytes, totalBytesRead, formDataLength);
totalBytesRead += byteRead;
String file = new String(dataBytes);
String saveFile = file.substring(file.indexOf("filename=\"") + 10);
saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1,saveFile.indexOf("\""));
int lastIndex = contentType.lastIndexOf("=");
String boundary = contentType.substring(lastIndex + 1,contentType.length());
int pos;
pos = file.indexOf("filename=\"");
pos = file.indexOf("\n", pos) + 1;
pos = file.indexOf("\n", pos) + 1;
pos = file.indexOf("\n", pos) + 1;
int boundaryLocation = file.indexOf(boundary, pos) - 4;
int startPos = ((file.substring(0, pos)).getBytes()).length;
int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;
FileOutputStream fileOut = new FileOutputStream("c:\\JBoss\\jboss-4.0.5.GA\\bin\\Fastran\\" + userEmail + "\\" + saveFile);
fileOut.write(dataBytes, startPos, (endPos - startPos));
fileOut.flush();
fileOut.close();
%>
<img src="logo.jpeg" width="101" height="75" align = "Right">
<img src="h_corporate_center.jpg" width="622" height="102">
<br><br><br><br>
<b>
<%
out.println("File uploaded as "+" \"" +saveFile+" \"");
%>
<br><br>
<b>Please make sure all required files are uploaded:<br>
<font color = "Red">ftn03, ftn07, and ftn09<font>
<br><br><br><br>
<input type=button onClick="location.href='fastran.jsp'" value='Proceed'>
</body>
</html>
the input files are a bunch of text files, with a lot of numbers generated through some other software. There can be some big files (perhaps close to a GB), and the upload time for such a file is painfully long - something like 6 min, over LAN. I have tried to upload it on my own computer(with application server running on it) and for a 50 MB file, it is taking about 3 min.
There are many third part options are available but that requires some librarires, and this code doesn't. So my preference is for this one.
Also, I couldn't figure out exactly, but some articles were suggesting to use String buffers instead of just Strings. In my case, Strings are used.
Secondly, I understand using of input and output buffer stream, but can it be the cause of long upload time? I mean converting a file to some machine independent code and then re-converting it back. If yes, can there be a way of skipping that all together ?
I am a bit hesitant of asking questions, my previous experience here was not a very pleasant one. Some genius, bullied me around :)
I will appreciate any help, thanks :)
Message was edited by:
NasirMunir
Similar Messages
-
Flash 8 file upload .doc & .pdf help, please
I've been working with the file upload sample that came with
Flash 8 as well
as other sources to help me figure this one out... like:
http://www.flash-db.com/Tutorials/upload/index.php
Everything I seem to find out about file uploading with Flash
specifically
deals with images, but I need to upload .doc & .pdf files
to attach to an
email as part of an employment application process for a site
that is built
with Flash.
The back-end script is a simple ColdFusion file that I've
tested (and works
fine with a static HTML test page):
<cffile action="upload"
destination = "ServerAddressHERE"
accept = "image/jpg, application/msword, application/pdf"
fileField = "Form.resumeFile"
nameConflict = "Overwrite">
The Flash example script that comes with Flash 8 has been
modified as
follows:
System.security.allowDomain(" FQDN_here");
import flash.net.FileReference;
// The listener object listens for FileReference events.
var listener:Object = new Object();
// When the user selects a file, the onSelect() method is
called, and
// passed a reference to the FileReference object.
listener.onSelect = function(selectedFile:FileReference):Void
// Update the TextArea to notify the user that Flash is
attempting to
// upload the image.
statusArea.text += "Attempting to upload " +
selectedFile.name + "\n";
// sample code provided by Flash
selectedFile.upload("
http://www.helpexamples.com/flash/file_io/uploadFile.php");
// my modification here (I have tried absolute references as
well):
selectedFile.upload("upfile.cfm");
listener.onOpen = function(selectedFile:FileReference):Void {
statusArea.text += "Opening " + selectedFile.name + "\n";
// Once the file has uploaded, the onComplete() method is
called.
listener.onComplete =
function(selectedFile:FileReference):Void {
// Notify the user that Flash is starting to download the
image.
statusArea.text += "Downloading " + selectedFile.name + " to
player\n";
// this part is irrelevant to my needs and I've worked with
and without it
imagesCb.addItem(selectedFile.name);
imagesCb.selectedIndex = imagesCb.length - 1;
downloadImage();
var imageFile:FileReference = new FileReference();
imageFile.addListener(listener);
uploadBtn.addEventListener("click", uploadImage);
// this part is irrelevant to my needs and I've worked with
and without it
imagesCb.addEventListener("change", downloadImage);
imagePane.addEventListener("complete", imageDownloaded);
function imageDownloaded(event:Object):Void {
if(event.total == -1) {
imagePane.contentPath = "Message";
// this part is where I added the extensions I need:
function uploadImage(event:Object):Void {
imageFile.browse([{description: "Image Files", extension:
"*.jpg;*.gif;*.png;*.doc;*.pdf,"}]);
ANY ideas would be sincerely appreciated... even if it's just
to confirm
that the Flash file upload process ONLY works with image
files.... Thank you
ALL in advance for ANY help I can get. :-)Did you ever get your issue with the F12, publish preview,
not loading your browser? I have just upgraded from MX 2004 to 8
and now have this issue.
T Peluso
[email protected] -
Servlet file uploading code need.
Hello
Can somebody give me a sourcecode of working servlet program that do file uploading on the server?
thnksHe's not angry at you, he's just angry at the self-serving tone of your post.
Why don't you give me a $100 USD... while at it? Oh, no? But WHY? Why oh why? I'm such a good person of liberal character - could you give me a 100 dollars RIGHT NOW? Oh, you wouldn't - I see...
Almost the same w/that "give me source code" :).... -
What's the error of this file-upload code?
hi,
I have written following code for file selection:
<form action="display.jsp" method="POST" enctype="multipart/form-data">
<input type="file" name="File1">
<input type="submit" name = "button" value="Submit">
</form>And my project another file display.jsp which code is:
<%@ page import="org.apache.commons.fileupload.*"%>
<%@page import="java.io.*" %>
<%@page import="java.util.*" %>
<%
out.println("Content Type: "+request.getContentType());
boolean isMultipart=FileUpload.isMultipartContent(request);
DiskFileUpload upload=new DiskFileUpload();
List items=upload.parseRequest(request);
Iterator iter=items.iterator();
while(iter.hasNext()){
FileItem item=(FileItem)iter.next();
if(item.isFormField()){
out.println("SIZE: "+item.getSize());
File fNew= new File(application.getRealPath("/"), item.getName());
out.println(fNew.getAbsolutePath());
item.write(fNew);
else
out.println("Field ="+item.getFieldName());
%>After that, i put on common-fileupload-1.1..jar on the project's /WebConcontent/WEB-INF/lib/ directory. And i have also add the common--fileupload-1.1.1. jar in the project build path. Further that i have got following error:
Error is:
exception
org.apache.jasper.JasperException: org/apache/commons/io/output/DeferredFileOutputStream
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:510)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:375)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:314)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:264)
javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
root cause
javax.servlet.ServletException: org/apache/commons/io/output/DeferredFileOutputStream
org.apache.jasper.runtime.PageContextImpl.doHandlePageException(PageContextImpl.java:858)
org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:791)
org.apache.jsp.display_jsp._jspService(display_jsp.java:78)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:97)
javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:332)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:314)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:264)
javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
root cause
java.lang.NoClassDefFoundError: org/apache/commons/io/output/DeferredFileOutputStream
org.apache.commons.fileupload.DefaultFileItemFactory.createItem(DefaultFileItemFactory.java:102)
org.apache.commons.fileupload.FileUploadBase.createItem(FileUploadBase.java:500)
org.apache.commons.fileupload.FileUploadBase.parseRequest(FileUploadBase.java:367)
org.apache.commons.fileupload.FileUploadBase.parseRequest(FileUploadBase.java:268)
org.apache.jsp.display_jsp._jspService(display_jsp.java:53)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:97)
javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:332)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:314)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:264)
javax.servlet.http.HttpServlet.service(HttpServlet.java:802)Why i have got this error? IS there anybody can help me? What will be the solution?Please Help me?
With regards
Binajava.lang.NoClassDefFoundError: org/apache/commons/io/output/DeferredFileOutputStream
Means you are missing a class file from the class path. Most likely cause is a missing jar file. The Apache Commons utilities often have dependancies on other Commons projects. This looks like it is looking for the Apache Commons IO jar file. Download the jar file and add it to the WEB-INF/lib directory. -
Hi,
I'm trying to track down where, i.e. by which code, image files are saved into the wiki.
I've traced the route to the wiki.js file which creates the dialogue that posts the form to the server but I've run into a wall.
I can't establish the name of the 'action' for the form.
Nor can I infer which python code is receiving it.
Can anyone help?
p.s. The reason for all this is that I want uploaded files to be namable, either manually or driven by a field in the form.
I guess this may involve rewriting some Python and I know that this is frowned upon but the look-out is mine!
p.p.s. It would also be nice to know where dialogManager() is defined, that's got me beaten at the moment.John Anderson1 wrote:
Remember that, when changing the code, you should override the code using your own theme; don't change it directly. Changing the uncompressed JavaScript won't work anyway; the server sends out code-compressed scripts whenever possible. Changing source code maintained by automatic software updates is the first of many steps down the path toward a bricked server.
Yes, I'm starting to get a hang of this (I think) I do intend to override the js, it's just I need to know how it's doing it in order to overrride it!
The form's "action" is "images"
I'd sort of deduced this but I can't find the code on the server that implements it. I did a quick search and couldn't find "images' in Python and deduced I was being a bit simplistic.
and dialogManager is defined in widgets.js:
var ModalDialogManager = Class.createWithSharedInstance('dialogManager');
Ah, thanks, I'll follow it up.
You do know that you can just name the file in the Finder before uploading it, right?
Not really. Under certain circumstances I want teamsserver to save the image file, in the page's image folder, with a particular name, i.e. NOT 123456.gif but pageImage.gif. I recognise that one has the potential problem of duplicate filenames but I'm happy to overwrite existing files AND I'm quite happy for teamsserver to give the file a unique name (presumably for internal database purposes) and make a duplicate of the numbered filename. i.e. save 123456.gif as per normal and then, if some condition is met (e.g. the alt name == pageimage) save a copy as pageImage.gif
(If you're interested, I've managed to get search to take an additional parameter xslFile=1...5 which selects alternate search.xsl files that return different search layouts. One of which substitutes page specific images instead of the generic 'snowflake' image in search listings. Currently I have to give each page a tag that specifies what the pageImage uid is, but this is wasteful as every tag in every page is therefore different. What I'm trying to do now is make the pageImage filename consistent so that I have a single tag that indicates every page that has an associated image. (The custom search.xsl files recognise if a page HAS a custom image and uses the snowflake if it doesn't)
Basically it allows me to generate slightly more attractive listings - nothing big but nice for my 'list of published books' page. Vanity, vanity)
Thanks for hte help. I'll follow it up tomorrow. -
[Sorry 'bout my bad English]
I'm trying to upload a file in a JSP. This page do a post to another JSP. In this page I have the code (there is more):
1)PrintWriter pw = new PrintWriter(
2) new BufferedWriter(new FileWriter( file)));
3) ServletInputStream in = request.getInputStream();
4) int i = in.read(); // here I got the error
5) while ( i != -1 ) {
6) pw.print((char) i);
7) i = in.read();
8) }
I got an error that the file was not open, so I run the page in the debug mode, and I notice that the lenght of 'in', just after line 3, is 0.
Please help
thank you.read this. its 4 pages. tells ya everything you need to know.
http://www.onjava.com/pub/a/onjava/2001/04/05/upload.html?page=1
-S- -
Keep Getting Annoying Image/File Upload Error Please Help!
I keep getting this error message - can't upload image X.png, it seems to happen with several different image - then I try to resume/retry wait some time; sometimes it works and sometimes it doesn't, getting kind of frustrating. Please help!
http://chefagogo.businesscatalyst.com/Hi
Are you still facing the same issue ?
It can be due to few reasons such as connectivity issues or if any update to your site is done at the same time from BC end.
If still you are facing same error, please let me know.
Thanks,
Sanjit -
Yet again the issue of file upload...?:|
I am trying to use a file upload as part of my screenflow.
I besically have 2 jsp files. jsp file upload code and the supporting HTML.
I created 2 "interactive component calls", connected with a transition and in the 1st one I call one JSP and in the 2nd one the other JSP.
My action on my HTML is action="fileupload.jsp" (my upload code file) I try changing it to action="<f:postResults />" but that didnt work
Then I changed my action to "<f:postResults fowardUrl="fileupload.jsp"/> I got an error on that too.
Anyone can help with that issue? I am besically tring to do a simple file upload from my sub-process.
Thank You
LilachHi,
There was a sample application regarding File Upload in Fuego 5.5. My mail id is [email protected] If you want then drop me a mail and I can send across the export of the same to you. -
Using BAPI functions BSP file upload
Hello,
Can anyone clarify me that ' can I upload a file form front end using BSP to the BP as backend to store e the image using the BAPI functions. All this is to get each BP photo in the Solution manager.
or I have use the datasets for the file upload. Please help me out.
With best regards,
SuneethaHi,
Uploading LOGO in SAP
http://www.sap-img.com/ts001.htm
Upload graphics on
The program RSTXLDMC can be used to upload graphics (file extension .tif on PC files) into individual standard text.
<b>ws_upload</b>
Transfer files from the frontend to the application server.
Rgds,
Prakash -
hi everbody,
i had deployed the file upload code in unix server and the page is successfully opening after attaching functions and menus. Now the page has only messagefileupload type item for file upload. so please please can anybody tell how to upload the file to a specific directory. my code i have used is in application module is like this but after selecting a file and click submit the file is not being uploaded.
String path= "/u03/prodcomn/temp/"+fileName;
if(testprofile != null){
System.out.println("path.."+path);
FileOutputStream fileOutput = new FileOutputStream(path);
fileOutput.write(blobIn.toByteArray());
fileOutput.close();
}the above code is perfectly correct and it is working , the silly thing that i didnt notice is in winscp i didnt refresh and see after file upload in the page.
i had wasted whole one day for this.
thanks
prabhakaranp -
For the last 3-4 weeks we have a web app that can longer upload largish files (e.g. 35mb PDF) via a web form Uploads no problem via SFTP.
Adobe so far has provided to answers and can't reproduce the problem.
Yet we (in Auckland) and our client in Wellington have the same problem.
Is there an issue with AWS Sydney, Adobe's setup or has BC introduced some new throttling or security rules around file uploads?
Any help greatly appreciated.Hi,
Please try to use the UI element "Office Control" of a web dynpro view.
For more details, refer to the web dynpro component: IOS_TEST_HELLOWORLD_MS.
Best regards,
Shalini. -
HELP! File Upload Servlet and Internet Explorer
Hello people. I hope this is an easy problem to solve...
I have a servlet upload program that works using Mozilla browser (www.mozilla.org), but for some reason it doesn't work using Microsoft IE. The servlet is also using the servlet upload API from Apache (commons).
I'm using IE version 6.0.2800.1106 in a Win98SE host computer. I get a cannot find path specified error message (see below). At work, I also get the same error message using IE, but don't know what version. The OS is XP. Unfortunately, at work, I can't install Mozilla browser (or any software-company policy) to see if Mozilla works there too. I would've like to have tested to see if the upload program worked on Mozilla on a truly remote computer.
So I figured, it must be a IE configuration issue, but darn it!! I began by resetting IE to default settings, but still have the problem, I played around with several different combinations of settings in "Tools"-->"Internet Options...", and I still get the error message. Someone PLEASE HELP ME!!!
Dunno, if it will help, I've also pasted the upload servlet source code below and the html file that's calling the upload servlet, but you still need the Apache commons file upload API.
Trust me on this one folks, for some reason it works for Mozilla, but not for IE. With IE, I can at least access web server, and therefore, the html file that calls the upload servlet , so I don't think it's a Tomcat configuration issue (version 5.0). I actually got the code for the file upload servlet from a book relatively new in the market (printed in 2003), and it didn't mention any limitations as far as what browser to use or any browser configuration requirements. I have e-mailed the authors, but they probably get a ton of e-mails...
Anyone suggestions?
Meanwhile, I will try to install other free browsers and see if the file upload program works for them too.
ERROR MESSAGE:
"HTTP Status 500 -
type Exception report
message
description The server encountered an internal error () that prevented it from fulfilling this request.
exception
javax.servlet.ServletException: C:\TOMCAT\webapps\MyWebApps\files\C:\WINDOWS\Desktop\myfile.zip (The system cannot find the path specified)
com.jspbook.FileUploadCommons.doPost(FileUploadCommons.java:43)
javax.servlet.http.HttpServlet.service(HttpServlet.java:763)
javax.servlet.http.HttpServlet.service(HttpServlet.java:856)
root cause
java.io.FileNotFoundException: C:\TOMCAT\webapps\MyWebApp\files\C:\WINDOWS\Desktop\myfile.zip (The system cannot find the path specified)
java.io.FileOutputStream.open(Native Method)
java.io.FileOutputStream.(FileOutputStream.java:176)
java.io.FileOutputStream.(FileOutputStream.java:131)
org.apache.commons.fileupload.DefaultFileItem.write(DefaultFileItem.java:392)
com.jspbook.FileUploadCommons.doPost(FileUploadCommons.java:36)
javax.servlet.http.HttpServlet.service(HttpServlet.java:763)
javax.servlet.http.HttpServlet.service(HttpServlet.java:856)
note The full stack trace of the root cause is available in the Tomcat logs.
Apache Tomcat 5.0.16"
FILE UPLOAD SERVLET source code:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import org.apache.commons.fileupload.*;
import java.util.*;
public class FileUploadCommons extends HttpServlet {
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.print("File upload success. <a href=\"/MyWebApp/files/");
out.print("\">Click here to browse through all uploaded ");
out.println("files.</a><br>");
ServletContext sc = getServletContext();
String path = sc.getRealPath("/files");
org.apache.commons.fileupload.DiskFileUpload fu = new
org.apache.commons.fileupload.DiskFileUpload();
fu.setSizeMax(-1);
fu.setRepositoryPath(path);
try {
List l = fu.parseRequest(request);
Iterator i = l.iterator();
while (i.hasNext()) {
FileItem fi = (FileItem)i.next();
fi.write(new File(path, fi.getName()));
catch (Exception e) {
throw new ServletException(e);
out.println("</html>");
public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException {
doPost(request, response);
HTML PAGE that calls the upload servlet:
<html>
<head>
<title>Example HTML Form</title>
</head>
<body>
<p>Select a file to upload or browse
currently uploaded files.</p>
<form action="http://##.##.##.####/MyWebApp/FileUploadCommons"
method="post" enctype="multipart/form-data">
File: <input type="file" name="file"><br>
<input value="Upload File" type="submit">
</form>
</body>
</html>
Thanks in advance for any assistance.
-DanI'm guessing what is happening is that Mozilla tells the servlet "here comes the file myfile.zip". The servlet builds a file name for it:
String path = sc.getRealPath("/files");
// path is now C:\TOMCAT\webapps\MyWebApps\files\
fi.write(new File(path, fi.getName()));
// append myfile.zip to "path", making it C:\TOMCAT\webapps\MyWebApps\files\myfile.zipIE, however, tells "here comes the file C:\WINDOWS\Desktop\myfile.zip". Now imagine what the path+filename ends up being...
So what you want to do is something along the lines of (assuming Windoze):
public static String basename(String filename)
int slash = filename.lastIndexOf("\\");
if (slash != -1)
filename = filename.substring(slash + 1);
// I think Windows doesn't like /'s either
int slash = filename.lastIndexOf("/");
if (slash != -1)
filename = filename.substring(slash + 1);
// In case the name is C:foo.txt
int slash = filename.lastIndexOf(":");
if (slash != -1)
filename = filename.substring(slash + 1);
return filename;
fi.write(new File(path, basename(fi.getName()));
....You can make the file name check more bomb proof if security is an issue. Long file names trying to overflow something in the OS, NUL characters, Unicode, forbidden names in Windos (con, nul, ...), missing file name, ... -
Problem with Multi File upload example, help needed
I got the code from the following location.....
http://www.adobe.com/devnet/coldfusion/articles/multifile_upload.html
And I've got it to work to some degree except I cant get the file transfer to work when pressing, Upload. Below is what my debugger outputs. Any thoughts on how to fix this or even what it means?
At the very bottom of this message is the upload.cfm code.......
Thanks in advance for the help
<html>
<head>
<title>Products - Error</title>
</head>
<body>
<h2>Sorry</h2>
<p>An error occurred when you requested this page.
Please email the Webmaster to report this error.
We will work to correct the problem and apologize
for the inconvenience.</p>
<table border=1>
<tr><td><b>Error Information</b> <br>
Date and time: 12/07/09 22:25:51 <br>
Page: <br>
Remote Address: 67.170.79.241 <br>
HTTP Referer: <br>
Details: ColdFusion cannot determine how to process the tag <CFDOCUMENT>. The tag name may be misspelled.<p>If you are using tags whose names begin with CF but are not ColdFusion tags you should contact Allaire Support. <p>The error occurred while processing an element with a general identifier of (CFDOCUMENT), occupying document position (41:4) to (41:70).<p>The specific sequence of files included or processed is:<code><br><strong>D:\hshome\edejham7\edeweb.com\MultiFileUpload\upload.cfm </strong></code><br>
<br>
</td></tr></table>
</body>
</html>
<!---
Flex Multi-File Upload Server Side File Handler
This file is where the upload action from the Flex Multi-File Upload UI points.
This is the handler the server side half of the upload process.
--->
<cftry>
<!---
Because flash uploads all files with a binary mime type ("application/ocet-stream") we cannot set cffile to accept specfic mime types.
The workaround is to check the file type after it arrives on the server and if it is non desireable delete it.
--->
<cffile action="upload"
filefield="filedata"
destination="#ExpandPath('\')#MultiFileUpload\uploadedfiles\"
nameconflict="makeunique"
accept="application/octet-stream"/>
<!--- Begin checking the file extension of uploaded files --->
<cfset acceptedFileExtensions = "jpg,jpeg,gif,png,pdf,flv,txt,doc,rtf"/>
<cfset filecheck = listFindNoCase(acceptedFileExtensions,File.ServerFileExt)/>
<!---
If the variable filecheck equals false delete the uploaded file immediatley as it does not match the desired file types
--->
<cfif filecheck eq false>
<cffile action="delete" file="#ExpandPath('\')#MultiFileUpload\uploadedfiles\#File.ServerFile#"/>
</cfif>
<!---
Should any error occur output a pdf with all the details.
It is difficult to debug an error from this file because no debug information is
diplayed on page as its called from within the Flash UI. If your files are not uploading check
to see if an errordebug.pdf has been generated.
--->
<cfcatch type="any">
<cfdocument format="PDF" overwrite="yes" filename="errordebug.pdf">
<cfdump var="#cfcatch#"/>
</cfdocument>
</cfcatch>
</cftry>Just 2 things in my test:
1) I use no accept attribute. Coldfusion is then free to upload any extenstion.
Restricting the type to application/octet-stream may generate errors. Also, it is unnecessary, because we perform a type check anyway.
2) I have used #ExpandPath('.')#\ in place of #ExpandPath('\')#
<cfif isdefined("form.filedata")>
<cftry>
<cffile action="upload"
filefield="filedata"
destination="#expandPath('.')#\MultiFileUpload\uploadedfiles\"
nameconflict="makeunique">
<!--- Begin checking the file extension of uploaded files --->
<cfset acceptedFileExtensions = "jpg,jpeg,gif,png,pdf,flv,txt,doc,rtf"/>
<cfset filecheck = listFindNoCase(acceptedFileExtensions,File.ServerFileExt)/>
<!---
If the variable filecheck equals false delete the uploaded file immediatley as it does not match the desired file types
--->
<cfif filecheck eq false>
<cffile action="delete" file="#ExpandPath('.')#\MultiFileUpload\uploadedfiles\#File.ServerFile#"/>
<cfoutput>Uploaded file deleted -- unacceptable extension (#ucase(File.ServerFileExt)#)</cfoutput>.<br>
</cfif>
Upload process done!
<cfcatch type="any">
There was an error!
<cfdocument format="PDF" overwrite="yes" filename="errordebug.pdf">
<cfdump var="#cfcatch#"/>
</cfdocument>
</cfcatch>
</cftry>
<cfelse>
<form method="post" action=<cfoutput>#cgi.script_name#</cfoutput>
name="uploadForm" enctype="multipart/form-data">
<input name="filedata" type="file">
<br>
<input name="submit" type="submit" value="Upload File">
</form>
</cfif> -
Help with File Upload manually
Hi Experts,
I need code to upload a file without using the upload UI Element. we have our terms and conditions which has to be signed by the user and once the user signs and clicks the next button to go to the next page, I generate a pdf with the time stamp of when the user signed and upload it to ECC. here i can not use the File upload UI Element but have to upload it automatically to ECC.
Can any one help me out with this please.
ThanksHi,
I dont know why you need to to upload the file for this requirement. You can simply store the user id and the timestamp in portal database table or in a ECC z table.
In case you definitely need to upload the file then you can use KM API to uploadthe file to portal KM folder
http://www.sdn.sap.com/irj/scn/go/portal/prtroot/docs/library/uuid/a099a3bd-17ef-2b10-e6ac-9c1ea42af0e9?quicklink=index&overridelayout=true
but you need not use the upload feature in the example, instead just get the data from wd context and upload to KM.
Srini -
Useful Code of the Day: Multipart Form File Upload
So, you want to upload files to your web server, do ya? Well, I've seen this topic posted a few times in the last month or so and many of the response I've seen here haven't included definitive answers. Of course, the actual problems vary, but ultimately, a bunch of people want to do file upload from an applet or application to an existing file upload script (CGI, PHP, JSP, etc.) on a web server. And invariably, there are problems with formatting the HTTP request to get things working.
Well, I had a need to do the same thing. I realize there are other solutions out there, such as some sample code that comes with Jakarta Commons Upload. But since we all like reusable code, and we also all seem to like reinventing wheels, here's my go at it: MultiPartFormOutputStream!
MultiPartFormOutputStream is a specialized OutputStream-like class. You create your URLConnection to the server (a static method included can do this for a URL for you, as some of the settings, doInput and doOutput specifically, seem to confuse people). Then get the OutputStream from it and create a boundary string (a static method to create one is provided as well) and pass them to the constructor. Now you have a MultiPartFormOutputStream which you can use to write form fields like text fields, checkboxes, etc., as well as write file data (from Files, InputStreams or raw bytes).
There are some convenience methods for writing primative type values as well as strings, but any higher level objects (aside from Files or InputStreams) aren't supported. (You can always serialize and pass the raw bytes.)
Sample usage code is below. Also, any recommendations for improvement are requested. The code was tested with the Jakarta Struts.
import java.io.*;
import java.net.*;
* <code>MultiPartFormOutputStream</code> is used to write
* "multipart/form-data" to a <code>java.net.URLConnection</code> for
* POSTing. This is primarily for file uploading to HTTP servers.
* @since JDK1.3
public class MultiPartFormOutputStream {
* The line end characters.
private static final String NEWLINE = "\r\n";
* The boundary prefix.
private static final String PREFIX = "--";
* The output stream to write to.
private DataOutputStream out = null;
* The multipart boundary string.
private String boundary = null;
* Creates a new <code>MultiPartFormOutputStream</code> object using
* the specified output stream and boundary. The boundary is required
* to be created before using this method, as described in the
* description for the <code>getContentType(String)</code> method.
* The boundary is only checked for <code>null</code> or empty string,
* but it is recommended to be at least 6 characters. (Or use the
* static createBoundary() method to create one.)
* @param os the output stream
* @param boundary the boundary
* @see #createBoundary()
* @see #getContentType(String)
public MultiPartFormOutputStream(OutputStream os, String boundary) {
if(os == null) {
throw new IllegalArgumentException("Output stream is required.");
if(boundary == null || boundary.length() == 0) {
throw new IllegalArgumentException("Boundary stream is required.");
this.out = new DataOutputStream(os);
this.boundary = boundary;
* Writes an boolean field value.
* @param name the field name (required)
* @param value the field value
* @throws java.io.IOException on input/output errors
public void writeField(String name, boolean value)
throws java.io.IOException {
writeField(name, new Boolean(value).toString());
* Writes an double field value.
* @param name the field name (required)
* @param value the field value
* @throws java.io.IOException on input/output errors
public void writeField(String name, double value)
throws java.io.IOException {
writeField(name, Double.toString(value));
* Writes an float field value.
* @param name the field name (required)
* @param value the field value
* @throws java.io.IOException on input/output errors
public void writeField(String name, float value)
throws java.io.IOException {
writeField(name, Float.toString(value));
* Writes an long field value.
* @param name the field name (required)
* @param value the field value
* @throws java.io.IOException on input/output errors
public void writeField(String name, long value)
throws java.io.IOException {
writeField(name, Long.toString(value));
* Writes an int field value.
* @param name the field name (required)
* @param value the field value
* @throws java.io.IOException on input/output errors
public void writeField(String name, int value)
throws java.io.IOException {
writeField(name, Integer.toString(value));
* Writes an short field value.
* @param name the field name (required)
* @param value the field value
* @throws java.io.IOException on input/output errors
public void writeField(String name, short value)
throws java.io.IOException {
writeField(name, Short.toString(value));
* Writes an char field value.
* @param name the field name (required)
* @param value the field value
* @throws java.io.IOException on input/output errors
public void writeField(String name, char value)
throws java.io.IOException {
writeField(name, new Character(value).toString());
* Writes an string field value. If the value is null, an empty string
* is sent ("").
* @param name the field name (required)
* @param value the field value
* @throws java.io.IOException on input/output errors
public void writeField(String name, String value)
throws java.io.IOException {
if(name == null) {
throw new IllegalArgumentException("Name cannot be null or empty.");
if(value == null) {
value = "";
--boundary\r\n
Content-Disposition: form-data; name="<fieldName>"\r\n
\r\n
<value>\r\n
// write boundary
out.writeBytes(PREFIX);
out.writeBytes(boundary);
out.writeBytes(NEWLINE);
// write content header
out.writeBytes("Content-Disposition: form-data; name=\"" + name + "\"");
out.writeBytes(NEWLINE);
out.writeBytes(NEWLINE);
// write content
out.writeBytes(value);
out.writeBytes(NEWLINE);
out.flush();
* Writes a file's contents. If the file is null, does not exists, or
* is a directory, a <code>java.lang.IllegalArgumentException</code>
* will be thrown.
* @param name the field name
* @param mimeType the file content type (optional, recommended)
* @param file the file (the file must exist)
* @throws java.io.IOException on input/output errors
public void writeFile(String name, String mimeType, File file)
throws java.io.IOException {
if(file == null) {
throw new IllegalArgumentException("File cannot be null.");
if(!file.exists()) {
throw new IllegalArgumentException("File does not exist.");
if(file.isDirectory()) {
throw new IllegalArgumentException("File cannot be a directory.");
writeFile(name, mimeType, file.getCanonicalPath(), new FileInputStream(file));
* Writes a input stream's contents. If the input stream is null, a
* <code>java.lang.IllegalArgumentException</code> will be thrown.
* @param name the field name
* @param mimeType the file content type (optional, recommended)
* @param fileName the file name (required)
* @param is the input stream
* @throws java.io.IOException on input/output errors
public void writeFile(String name, String mimeType,
String fileName, InputStream is)
throws java.io.IOException {
if(is == null) {
throw new IllegalArgumentException("Input stream cannot be null.");
if(fileName == null || fileName.length() == 0) {
throw new IllegalArgumentException("File name cannot be null or empty.");
--boundary\r\n
Content-Disposition: form-data; name="<fieldName>"; filename="<filename>"\r\n
Content-Type: <mime-type>\r\n
\r\n
<file-data>\r\n
// write boundary
out.writeBytes(PREFIX);
out.writeBytes(boundary);
out.writeBytes(NEWLINE);
// write content header
out.writeBytes("Content-Disposition: form-data; name=\"" + name +
"\"; filename=\"" + fileName + "\"");
out.writeBytes(NEWLINE);
if(mimeType != null) {
out.writeBytes("Content-Type: " + mimeType);
out.writeBytes(NEWLINE);
out.writeBytes(NEWLINE);
// write content
byte[] data = new byte[1024];
int r = 0;
while((r = is.read(data, 0, data.length)) != -1) {
out.write(data, 0, r);
// close input stream, but ignore any possible exception for it
try {
is.close();
} catch(Exception e) {}
out.writeBytes(NEWLINE);
out.flush();
* Writes the given bytes. The bytes are assumed to be the contents
* of a file, and will be sent as such. If the data is null, a
* <code>java.lang.IllegalArgumentException</code> will be thrown.
* @param name the field name
* @param mimeType the file content type (optional, recommended)
* @param fileName the file name (required)
* @param data the file data
* @throws java.io.IOException on input/output errors
public void writeFile(String name, String mimeType,
String fileName, byte[] data)
throws java.io.IOException {
if(data == null) {
throw new IllegalArgumentException("Data cannot be null.");
if(fileName == null || fileName.length() == 0) {
throw new IllegalArgumentException("File name cannot be null or empty.");
--boundary\r\n
Content-Disposition: form-data; name="<fieldName>"; filename="<filename>"\r\n
Content-Type: <mime-type>\r\n
\r\n
<file-data>\r\n
// write boundary
out.writeBytes(PREFIX);
out.writeBytes(boundary);
out.writeBytes(NEWLINE);
// write content header
out.writeBytes("Content-Disposition: form-data; name=\"" + name +
"\"; filename=\"" + fileName + "\"");
out.writeBytes(NEWLINE);
if(mimeType != null) {
out.writeBytes("Content-Type: " + mimeType);
out.writeBytes(NEWLINE);
out.writeBytes(NEWLINE);
// write content
out.write(data, 0, data.length);
out.writeBytes(NEWLINE);
out.flush();
* Flushes the stream. Actually, this method does nothing, as the only
* write methods are highly specialized and automatically flush.
* @throws java.io.IOException on input/output errors
public void flush() throws java.io.IOException {
// out.flush();
* Closes the stream. <br />
* <br />
* <b>NOTE:</b> This method <b>MUST</b> be called to finalize the
* multipart stream.
* @throws java.io.IOException on input/output errors
public void close() throws java.io.IOException {
// write final boundary
out.writeBytes(PREFIX);
out.writeBytes(boundary);
out.writeBytes(PREFIX);
out.writeBytes(NEWLINE);
out.flush();
out.close();
* Gets the multipart boundary string being used by this stream.
* @return the boundary
public String getBoundary() {
return this.boundary;
* Creates a new <code>java.net.URLConnection</code> object from the
* specified <code>java.net.URL</code>. This is a convenience method
* which will set the <code>doInput</code>, <code>doOutput</code>,
* <code>useCaches</code> and <code>defaultUseCaches</code> fields to
* the appropriate settings in the correct order.
* @return a <code>java.net.URLConnection</code> object for the URL
* @throws java.io.IOException on input/output errors
public static URLConnection createConnection(URL url)
throws java.io.IOException {
URLConnection urlConn = url.openConnection();
if(urlConn instanceof HttpURLConnection) {
HttpURLConnection httpConn = (HttpURLConnection)urlConn;
httpConn.setRequestMethod("POST");
urlConn.setDoInput(true);
urlConn.setDoOutput(true);
urlConn.setUseCaches(false);
urlConn.setDefaultUseCaches(false);
return urlConn;
* Creates a multipart boundary string by concatenating 20 hyphens (-)
* and the hexadecimal (base-16) representation of the current time in
* milliseconds.
* @return a multipart boundary string
* @see #getContentType(String)
public static String createBoundary() {
return "--------------------" +
Long.toString(System.currentTimeMillis(), 16);
* Gets the content type string suitable for the
* <code>java.net.URLConnection</code> which includes the multipart
* boundary string. <br />
* <br />
* This method is static because, due to the nature of the
* <code>java.net.URLConnection</code> class, once the output stream
* for the connection is acquired, it's too late to set the content
* type (or any other request parameter). So one has to create a
* multipart boundary string first before using this class, such as
* with the <code>createBoundary()</code> method.
* @param boundary the boundary string
* @return the content type string
* @see #createBoundary()
public static String getContentType(String boundary) {
return "multipart/form-data; boundary=" + boundary;
}Usage: (try/catch left out to shorten the post a bit)
URL url = new URL("http://www.domain.com/webems/upload.do");
// create a boundary string
String boundary = MultiPartFormOutputStream.createBoundary();
URLConnection urlConn = MultiPartFormOutputStream.createConnection(url);
urlConn.setRequestProperty("Accept", "*/*");
urlConn.setRequestProperty("Content-Type",
MultiPartFormOutputStream.getContentType(boundary));
// set some other request headers...
urlConn.setRequestProperty("Connection", "Keep-Alive");
urlConn.setRequestProperty("Cache-Control", "no-cache");
// no need to connect cuz getOutputStream() does it
MultiPartFormOutputStream out =
new MultiPartFormOutputStream(urlConn.getOutputStream(), boundary);
// write a text field element
out.writeField("myText", "text field text");
// upload a file
out.writeFile("myFile", "text/plain", new File("C:\\test.txt"));
// can also write bytes directly
//out.writeFile("myFile", "text/plain", "C:\\test.txt",
// "This is some file text.".getBytes("ASCII"));
out.close();
// read response from server
BufferedReader in = new BufferedReader(
new InputStreamReader(urlConn.getInputStream()));
String line = "";
while((line = in.readLine()) != null) {
System.out.println(line);
in.close();------
"Useful Code of the Day" is supplied by the person who posted this message. This code is not guaranteed by any warranty whatsoever. The code is free to use and modify as you see fit. The code was tested and worked for the author. If anyone else has some useful code, feel free to post it under this heading.I have a weird problem here. I'm using the Java POST (slightly altered for my purposes) mechanism but the receiving script doesn't receive any form variables (neither files nor regular form fields). If I try using the same receiving script with a regular upload form, it works. Because I've been pulling my hair out, I even went so far as to analyze the ip-packets. I can see that the file is actually sent through the Java POST mecahnism. Anybody any ideas. Here's the ip-packet of the failing upload:
----- Hypertext Transfer Protocol -----
HTTP: POST /fotoxs/upload.cfm HTTP/1.1
HTTP: Connection: Keep-Alive
HTTP: Content-Type: multipart/form-data; boundary=-----------------------------fb2649be18
HTTP: User-Agent: Mozilla/4.7 [en] (WinNT; U)
HTTP: Accept-Language: en-us
HTTP: Accept-Encoding: gzip, deflate
HTTP: Accept: image/gif, image/jpeg, image/pjpeg, */*
HTTP: CACHE-CONTROL: no-cache
HTTP: Host: newmarc
HTTP: Content-Length: 15511
----- Hypertext Transfer Protocol -----
HTTP: -----------------------------fb2649be18
HTTP: Content-Disposition: form-data; name="uploadFile"; filename="out.jpg"
HTTP: Content-Type: image/jpeg
HTTP: Data
....[data packets]
The one that works (from the regular post) is as follows:
----- Hypertext Transfer Protocol -----
HTTP: POST /fotoxs/upload.cfm HTTP/1.1
HTTP: Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-gsarcade-launch, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*
HTTP: Referer: http://localhost:8500/fotoxs/test.cfm
HTTP: Accept-Language: nl
HTTP: Content-Type: multipart/form-data; boundary=---------------------------7d41961f201c0
HTTP: Accept-Encoding: gzip, deflate
HTTP: User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)
HTTP: Host: newmarc
HTTP: Content-Length: 59022
HTTP: Connection: Keep-Alive
HTTP: Cache-Control: no-cache
----- Hypertext Transfer Protocol -----
HTTP: -----------------------------7d41961f201c0
HTTP: Content-Disposition: form-data; name="FiletoUpload"; filename="D:\My Documents\My Pictures\fotomarc.jpg"
HTTP: Content-Type: image/pjpeg
HTTP: Data
----- Hypertext Transfer Protocol -----
HTTP: HTTP/1.1 100 Continue
HTTP: Server: Microsoft-IIS/5.0
HTTP: Date: Sun, 07 Mar 2004 17:14:41 GMT
....[data packets]
One detail worth mentioning is that I don't read a file from harddisk, I'm streaming it directly to the connection outputstream from an image compression utility. But I can see the data in the ip-packets, and even if that somehow didn't work right, it doesn't explaing the fact that the receiving scripts reports no form fields whatsoever.
Thanks,
Marc
Maybe you are looking for
-
Don't use the Software Update in Preferences - download the Combo Updater !
Software Update failed and I had to archive/install back to 10.5 - just download the Combo Updater and you should be ok.
-
Mygrating Asset GL Balances from Legacy to SAP
Hello Gurus, We are Migrating GL balances from legacy system to SAP system. I would like to know whether there is any other transaction code other than OASV for fixed assets GL migration from Legacy to SAP system. Can we use F-02 transaction code for
-
I have photoshop elements 11 and I can not get the encoder to work
I have photoshop elements 11 and when I put the code in for the encode to be activation .It keeps coming up with the code is not right.
-
MARS 4.3 and NAC (CSACS 4.2) logging
Hi I'm trying to get MARS 4.3 and my Cisco ACS 4.2 server working together to display NAC events on MARS. I've added the server which runs CSACS under Security/Monitor Devices, added the reporting application of Cisco Secure ACS 3.x (does this matter
-
I recently bought a new iPad. When setting up Apple Account,the accounts details where I need to provide details of payment ,I have a challenge with info. Needed as ZIP,ADDRESS,PHONE NUMBER. This is so because my country Zambia is not among the many