Upload a file to the server - multipart/form-data ?
I need to upload a file from my local machine to the server from a jsp page. I was asked to use a form with ENCTYPE = "multipart/form-data". but I am not sure how it works. Can any one enlighten me on the process or is there any other way to do it.
null
You can find the jsp source & the java sources which exactly does that in the iFS CMS sample code section. Go to Products -> Internet File system -> sample code -> Content Management System. This application allows the user to upload files from a local file system into iFS. This application creates the file in the iFS repository. You may want to save it in the file system of the web server. You may have to make little changes but the functionality is exactly what you are looking for.
Hope this helps.
Rajesh
Similar Messages
-
How to Upload a File on the Server
Hi,
I want to upload a file on the server from Windows Mobile Application. Can anyone please suggest me a way to do so?
Thanks in advance,
Saheli SurFollowing links should also help
http://blog.anthonybaker.me/2013/06/how-to-upload-file-from-windows-phone.html
http://stackoverflow.com/questions/19954287/how-to-upload-file-to-server-with-http-post-multipart-form-data/20000831#20000831
Gaurav Khanna | Microsoft .NET MVP | Microsoft Community Contributor -
How to upload a file to the server using ajax and struts
With the following code iam able to upload a file ato the server.
But my problem is It is working fine if iam doing in my system nd when iam trying to
access theis application from someother system in our office which are connected through lan
iam getting an error called 500 i,e internal server error.
Why it is so???????
Plz help me????????
It is required in my project.
I want the code to access from every system.
My exact requirement is i have to upload a file to the server and retrive its path and show it in the same page from which we
have uploaded a file.
Here the file has to be uploaded to the upload folder which is present in the server.Iam using Tomcat server.
Any help highly appreciated.
Thanks in Advance
This is my input jsp
filename.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<script type="text/javascript">
alertflag = true;
var xmlHttp;
function startRequest(file1)
if(alertflag)
alert("file1");
alert(file1);
xmlHttp=createXmlHttpRequest();
var video=document.getElementById("filepath").value;
xmlHttp.open("POST","FilePathAction.do",true);
xmlHttp.onreadystatechange=handleStateChange;
xmlHttp.setRequestHeader('Content-Type', application/x-www-form-urlencoded');
xmlHttp.send("filepath="+file1);
function createXmlHttpRequest()
//For IE
if(window.ActiveXObject)
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
//otherthan IE
else if(window.XMLHttpRequest)
xmlHttp=new XMLHttpRequest();
return xmlHttp;
//Next is the function that sets up the communication with the server.
//This function also registers the callback handler, which is handleStateChange. Next is the code for the handler.
function handleStateChange()
var message=" ";
if(xmlHttp.readyState==4)
if(alertflag)
alert(xmlHttp.status);
if(xmlHttp.status==200)
if(alertflag)
alert("here");
document.getElementById("div1").style.visibility = "visible";
var results=xmlHttp.responseText;
document.getElementById('div1').innerHTML = results;
else
alert("Error loading page"+xmlHttp.status+":"+xmlHttp.statusText);
</script></head><body><form >
<input type="file" name="filepath" id="filepath" onchange="startRequest(this.value);"/>
</form>
<div id="div1" style="visibility:hidden;">
</div></body></html>
The corresponding action class is FIlePathAction
package actions;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
public class FilePathAction extends Action{
public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException
String contextPath1 = "";
String uploadDirName="";
String filepath="";
System.out.println(contextPath1 );
String inputfile = request.getParameter("filepath");
uploadDirName = getServlet().getServletContext().getRealPath("/upload");
File f=new File(inputfile);
FileInputStream fis=null;
FileOutputStream fo=null;
File f1=new File(uploadDirName+"/"+f.getName());
fis=new FileInputStream(f);
fo=new FileOutputStream(f1);
try
byte buf[] = new byte[1024*8]; /* declare a 8kB buffer */
int len = -1;
while((len = fis.read(buf)) != -1)
fo.write(buf, 0, len);
catch(Exception e)
e.printStackTrace();
filepath=f1.getAbsolutePath();
request.setAttribute("filepath", filepath);
return mapping.findForward("filepath");
Action-mappings in struts-config.xml
<action path="/FilePathAction"
type="actions.FilePathAction">
<forward name="filepath" path="/dummy.jsp"></forward>
</action>
and the dummy.jsp code is
<%=request.getAttribute("filepath")%>MESSAGE FROM THE FORUMS ADMINISTRATORS and COMMUNITY
This thread will be deleted within 24 business hours. You have posted an off-topic question in an area clearly designated for discussions
about Distributed Real-time Java. Community members looking to help you with your question won't be able to find it in this category.
Please use the "Search Forums" element on the left panel to locate a forum based on your topic. A more appropriate forum for this post
could be one of:
Enterprise Technologies http://forums.sun.com/category.jspa?categoryID=19
David Holmes -
Problem when I upload txt files to the server
Hi, I have a problem when I try to upload files to the server, and I can't understand the fail.
My case is:
I have a jsp page where a from is.
This form is sended to a servlet that proccess its content and upload the attach file to the server.
It works correctly (it uploads the files, txt, xls and csv), the problem is when I try to upload a txt file like this, for example:
Depth Age
0 0,1
2 0,9
3 2
5 6
6 9
8 12
34 25
56 39
101 40When I verify the uploaded file, this one has a character extra of return of line (a small square). This character prevents me from working then correctly with the file, on having detected a column of more.
Which can be the problem?
The code I use to uploaded the file is:
try
MyConnection Objconnection = new MyConnection();
boolean isMultipart = FileUpload.isMultipartContent(req);
// Create a factory for disk-based file items
FileItemFactory factory = new DiskFileItemFactory();
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// Set overall request size constraint
upload.setSizeMax(1024*512); //524288 Bytes (512 KB)
// Parse the request
List items = upload.parseRequest(req);
// Process the uploaded items
Iterator iter = items.iterator();
String dat = new String();
String typeFile = new String();
while (iter.hasNext())
FileItem item = (FileItem) iter.next();
if (item.getFieldName().equals("typeFile") )
typeFile = item.getString();
if (!item.isFormField())
String fieldName = item.getFieldName();
String fileName = item.getName();
String contentType = item.getContentType();
boolean isInMemory = item.isInMemory();
long sizeInBytes = item.getSize();
int numbers=0;
for(int i=fileName.length();(i=fileName.lastIndexOf('\\',i-1))>=0;)
numbers++;
String stringFile[] = fileName.split("\\\\");
HttpSession session = req.getSession(true);
String loginSesion = (String)session.getAttribute("UserLogin");
String newUserFolder = loginSesion;
File createFile = new File("/usr/local/tomcat/webapps/Usuarios/FilesUp/"+newUserFolder);
if ("AgeModel".equals(typeFile))
createFile = new File("/usr/local/tomcat/webapps/Usuarios/FilesUp/AgeModels/"+newUserFolder);
if (!createFile.exists())
createFile.mkdir();
fileName = stringFile[numbers];
File uploadedFile = new File("/usr/local/tomcat/webapps/Usuarios/FilesUp/"+newUserFolder+"/"+fileName);
if ("AgeModel".equals(typeFile) )
uploadedFile = new File("/usr/local/tomcat/webapps/Usuarios/FilesUp/AgeModels/"+newUserFolder+"/"+fileName);
existe = Objconnection.existFile(fileName, typeFile, loginSesion);
if ( true == existe )
exito = false;
else
item.write(uploadedFile);
....// NOW REGISTER THE FILE IN TH DATA BASE
} // if (!item.isFormField())
} // WHILE ( iter.hasNext() )
catch(Exception e) {
out.println("Error de Aplicaci�n " + e.getMessage());
return exito;
...THANKSHi,
Sorry I am aware this question was posted way back, but I am having similar problem and haven't been able to find the fix yet.
So please let me known if you have got any ideas.
My problem is same that I have to upload a CSV file from Client Machine (Windows) to Unix Application Server.
I am using JSP method post and multipart/form-data (as in http://www.roseindia.net/jsp/file_upload/Sinle_upload.xhtml.shtml).
The file is uploaded fine but the problem is it displays carraige Return (^M) a square boxes on Unix file.
I can't ask user to convert file to Unox format before uploading. They just convert excel file to CSV and upload.
Is there any way I can get rid of these characters as I have to use this file further.
Sorry, I can't use any paid utility or tool for it.
I would appreciate if you could please help.
Thanks,
SW -
Socket blocking on read operation while uploading zip file to the server
I am trying to upload a zip file to the server
Client thread creates the zip file ( of the modified files) and it even completes writing the data to the socket stream.
Now if the server thread tries to read the same data from the stream, it blocks on read operation.
While downloding the zip file from the server works fine.
Thanks in advanceYou can use the URL object to upload it as multipart/form-data.
http://forum.java.sun.com/thread.jspa?threadID=579720&messageID=3997264
Or check out some of the file uploaders out there.
http://www.google.nl/search?hl=nl&q=site%3Asun.com+upload+applet&btnG=Zoeken&meta= -
How can I upload a file to the server where I save the Java Web Start Files
Hello,
Does anyone knows how to upload a file to the directory where I save the JAR files through the Java Web Start program. Thanks youftp
-
Uploading a file to Portal server
Hello all:
First question: I'm creating an HTML page that uploads a file to the server using a form like this:
When user fills the form and sends the file and error is showed:
Application error occurred during request processing.
Details: Error [com.sap.engine.services.servlets_jsp.server.exceptions.WebServletException:
Error in dispatching request to servlet /servlet/com.citas.Citas.], with root cause java.lang.NullPointerException: null.
In the trace log file, appears an error message:
#1.5#000F20CF176F00470003A2D300000D900004310A97BCC911#1179821471985#com.sap.ip.collaboration.rtc#sap.com/irj#com.sap.ip.collaboration.rtc.class com.sap.ip.collaboration.core.api.rtmf.core.RTMFMessaging.JMSPolling.startRunning()#anonymous#0##portald.huc.es_EP6_7205750#Guest#ea1ca07002d011dccf9a000f20cf176f#Thread[Thread-70,5,SAPEngine_Application_Thread[impl:3]_Group]##0#0#Error##Java###Exception in method: javax.jms.JMSSecurityException: You do not have permissions: action create_queue and instance ALL.
#1#javax.jms.JMSSecurityException: You do not have permissions: action create_queue and instance ALL.
at com.sap.jms.protocol.notification.ServerExceptionResponse.getException(ServerExceptionResponse.java:231)
at com.sap.jms.client.session.Session.checkReceivedPacket(Session.java:2613)
at com.sap.jms.client.session.Session.createQueue(Session.java:2442)
at com.sap.ip.collaboration.core.api.rtmf.core.RTMFMessaging$JMSPolling.startRunning(RTMFMessaging.java:1130)
at com.sap.ip.collaboration.core.api.rtmf.core.RTMFMessaging$JMSPolling.run(RTMFMessaging.java:1067)
at java.lang.Thread.run(Thread.java:534)
I think the error is caused by an authotization problem, but I don't know how to solve it.
Second question: I'd like to know where is the default folder in the server where the files are uploaded in that way (HTML form). I don't know how to configure it. Maybe I could change permissions in it to allow Portal users to read/write in it.
Thank all in advance. Regards,
Alejandro Gómez.HI Alejandro
Refer to this thread may be of some help to you .
Authorization for JMS resources
Thanx
Pankaj -
H:form enctype="multipart/form-data" gets removed
I tried to create a file upload page using tomahawk 1.1.6, JSF RI 1.2_05-b06-FCS and facelets.
What I found is that the h:form removes the enctype="multipart/form-data" when rendering the JSF page.
In the resulting html page the enctype is entirely missing.
As a result the fileupload doesn't work, since the browser doesn't even send the file.
I read that JSF doesn't support multipart messages, but with this behaviour it prevents other libs like tomahawk accomplishing this task. Does anyone know whether there a way to solve this issue other then patching the FormRenderer?
regards,
ArturPlease log an issue [1] (if possible include a test case as an attachement).
[1] https://javaserverfaces.dev.java.net/issues -
What is multipart/form-data ?
what is multipart/form-data ?
generally A form have some input fields and a submit button ? but what is
multipart/form-data ? or is it same thing ?http://www.w3.org/TR/REC-html40/interact/forms.html
enctype = content-type
This attribute specifies the content type used to submit the form to the server (when the value of method is "post"). The default value for this attribute is "application/x-www-form-urlencoded". The value "multipart/form-data" should be used in combination with the INPUT element, type="file". -
Hi, I am using HP11 and iPlanet web server. When trying to upload files over HTTP using FORM ENCTYPE="multipart/form-data" that are bigger than a few Kilobytes i get a 408 error. (client timeout). It is as if the server has decided that the client has timed out during the file upload. The default setting is 30 seconds for AcceptTimeout in the magnus.conf file. This should be ample to get the file across, even increasing this to 2 minutes just produces the same error after 2 minutes. Any help appreciated. Apologies if this is not the correct forum for this, I couldn't see one for iPlanet and Web, many thanks, Kieran.
Hi,
You didnt mention which version of IWS. follow these steps.
(1)Goto Web Server Administration Server, select the server you want to manage.
(2)Select Preference >> Perfomance Tuning.
(3)set HTTP Persistent Connection Timeout to your choice (eg 180 sec for three minutes)
(4) Apply changes and restart the server.
*Setting the timeout to a lower value, however, may prevent the transfer of large files as timeout does not refer to the time that the connection has been idle. For example, if you are using a 2400 baud modem, and the request timeout is set to 180 seconds, then the maximum file size that can be transferred before the connection is closed is 432000 bits (2400 multiplied by 180)
Regards
T.Raghulan
[email protected] -
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 -
Hi There,
I am new to FLEX and also new to writing a client for a web service.
My question is more about flex (Flash builder 4.5) APIs, what APIs to use.
I want to access a web service, that's published here.
https://build.phonegap.com/docs/write_api
here is the description of webservice
===========
1) I have to do a post on POST https://build.phonegap.com/api/v1/apps
2) content type has to be "multipart/form-data"
3) JSON bodies of requests are expected to have the name 'data'
data will be someting like this
'data={"title":"API V1 App","package":"com.alunny.apiv1","version":"0.1.0","create_method":"file"}'
4) include a zip file in the multipart body of your post, with the parameter name 'file'.
===========
I want to make a 'multipart/form-data' Post and send
one string and one zip file.
My first question to self was If i send both string + binary data in the body ...
how will server understand where string end and where zip file starts?
Then read on W3.org( http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.2 )
How is text + binary data can be sent through "multipart/form-data" post requst.
there has to be some boundries.
After this I read and example in flex and tried following it.
http://codeio.wordpress.com/2010/04/03/5-minutes-on-adobe-flex-mimic-file-upload-for-in-me mory-contents/
but it doesn't seems to be working for me.
public function createNewApp(cb:Function , appFile : File):void
var service:HTTPService = new HTTPService();
service.url = ROOT+"apps";
service.showBusyCursor = true;
service.addEventListener(ResultEvent.RESULT, function(e:ResultEvent):void {
//translate JSON
trace(e.result);
var result:String = e.result.toString();
var data:Object = JSON.parse(result);
cb(data.link);
service.addEventListener(FaultEvent.FAULT, defaultFaultHandler); //todo : allow user to add his own as well
authAndUploadNewApp(service,appFile);
private function authAndUploadNewApp(service:HTTPService,appFile : File):void {
var encoder:Base64Encoder = new Base64Encoder();
encoder.encode(username + ":"+password);
service.headers = {Accept:"application/json", Authorization:"Basic " + encoder.toString()};
service.method ="POST";
var boundary:String = UIDUtil.createUID();
service.contentType = "multipart/form-data; boundary=—————————" + boundary;
var stream:FileStream = new FileStream();
stream.open(appFile, FileMode.READ);
var binaryData:ByteArray = new ByteArray();
var fileData : String = new String();
stream.readBytes(binaryData);
stream.close();
fileData = binaryData.readUTFBytes(binaryData.bytesAvailable); // I think this is where I have problem.... how do
//how do i converrt this bytearray/stream of data to string and send it in my post request's body - i guess if this step work rest should work..
var params: String = new String();
var content:String = "—————————" + boundary + "nr";
content += 'Content-Disposition: form-data; name="data";' + '{"title":"ELS test app 2","package":"com.elsapp.captivate","version":"12.3.09","create_method":"file"}' + "nr";
content += "—————————" + boundary + "nr";
content += 'Content-Disposition: form-data; name="file";' + fileData + "nr";
content += "—————————–" + boundary + "–nr";
service.request = content;
service.send();In the past I have used URLVariables with URLRequest and URLLoader to achieve this kind of requirement.
Check out http://livedocs.adobe.com/flex/3/html/help.html?content=17_Networking_and_communications_3 .html which should be useful. My preference has always been to use this style instead of HTTPService objects, giving you a little more control which is what you need here.
Let me know if you need any more assistance. -
How to open a file created at the server through form/report at client end
How to open a file created at the server through form/report at client end
Dear Sir/Madame,
I am creating a exception report at the server-end using utl file utility. I want to display this report at the client end. A user doesn't have any access to server. Will u please write me the solution and oblige me.
Thanks
Rajesh JainOne way of doing this is to write a PL/SQL procedure that uses UTL_FILE to read the file and DBMS_OUTPUT to display the contents to the users.
Cheers, APC -
Upload an excel file in the server with a background job
I am trying to upload an excel file in the server, but i only can upload flat files, i can upload files in local with the function ALSM_EXCEL_TO_INTERNAL_TABLE, can i use this function reading an excel file in the server, or is there another possibility of uploadinging an excel file in the server with a background job ?
thanks in advanceHi
First read the file from the server to some temporary place at presentation layer and then open it. And if required, save it to the server afterwards. To read/write files to application server you can use:
1. Statements "OPEN DATASET/CLOSE DATASET".
2. There are some FMs for server file operations, like "C13Z_FILE_UPLOAD_BINARY" and "C13Z_FILE_DOWNLOAD_BINARY".
*--Serdar -
Uploading a file to the web server
How can i upload a file to the web server using JSP.
hello sir,
Could U even tell me performance which one is better.
U have mentioned that Multipartrequest is Complex for Beginers,
but as far as performance is concerned which is better.
If Taglib is used is it error Free , as I do not know much abt taglib.
have just read a little abt it , have never created my own Custome Tag.
Could U just Guide me which is the best site where I could get know a little abt Taglib.An easy tutorial where I could read and start working on My application.
I have been given a Deadline. So Please help me man.
If U have the source Code for Uploading of a File Please Cut Paste it.
I have to finish the project on time .
Please
With Regards
Eklavya
Maybe you are looking for
-
Characters in a message with E6 Belle
Dear Users, I have updated my E6 to Nokia Belle, I notice that I'm not able to know how many characters used for a message in both languages (Arabic & English), Awaiting for your reply, Regards Solved! Go to Solution. Attachments: 14022012008.jpg 32
-
Import Data - slow, on error there is no way to stop
I just tried to import a CSV using SQL Developer. The UI didn't catch this error before starting: Error report: SQL Error: ORA-00972: identifier is too long 00972. 00000 - "identifier is too long" *Cause: An identifier with more than 30 characters
-
This is a weird one. When working with Dreamweaver (CS6), I sometimes get a message "This file has been modified outside Dreamweaver. Do you want to reload it?" It happens a lot if I do a search-and-replace with another program, like TextWrangler. If
-
Download window, show all downloads and Ctrl+F Search Menu
I click the little down arrow for downloads and a "show all downloads" thing pops up. Anyway to stop this and make it automatically show all downloads? Kind of annoying having to click twice to see my downloads. Also, I am using this: https://addons.
-
What is function consultant role in technical up grade
Hi All, Please share your experiences on upgrade project. What is function consultant role in technical up grade. Aditya.