Video Using HTML 5 and servlet - java

Below given code is for video streaming. This is fine with IE9 and firefox but it is not fine with Chrome and Mac Safari.
import java.io.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class VideoStreamServlet
*/
public class VideoStreamServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* Default constructor.
*/
public VideoStreamServlet() {
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String range = request.getHeader("range");
String browser = request.getHeader("User-Agent");
System.out.println(browser);
if(browser.indexOf("Firefox") != -1){
System.out.println("==========ITS FIREFOX=============");
byte[] data = getBytesFromFile(new File("D:/media/final.ogg"));
response.setContentType("video/ogg");
response.setContentLength(data.length);
response.setHeader("Content-Range", range + Integer.valueOf(data.length-1));
response.setHeader("Accept-Ranges", "bytes");
response.setHeader("Etag", "W/\"9767057-1323779115364\"");
byte[] content = new byte[1024];
BufferedInputStream is = new BufferedInputStream(new ByteArrayInputStream(data));
OutputStream os = response.getOutputStream();
while (is.read(content) != -1) {
//System.out.println("... write bytes");
os.write(content);
}
is.close();
os.close();
}
else if(browser.indexOf("Chrome") != -1){
System.out.println("==========ITS Chrome=============");
byte[] data = getBytesFromFile(new File("D:/media/final.mp4"));
String diskfilename = "final.mp4";
response.setContentType("video/mp4");
//response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename=\"" + diskfilename + "\"" );
System.out.println("data.length " + data.length);
response.setContentLength(data.length);
response.setHeader("Content-Range", range + Integer.valueOf(data.length-1));
response.setHeader("Accept-Ranges", "bytes");
response.setHeader("Etag", "W/\"9767057-1323779115364\"");
byte[] content = new byte[1024];
BufferedInputStream is = new BufferedInputStream(new ByteArrayInputStream(data));
OutputStream os = response.getOutputStream();
while (is.read(content) != -1) {
//System.out.println("... write bytes");
os.write(content);
}
is.close();
os.close();
}
else if(browser.indexOf("MSIE") != -1) {
System.out.println("==========ITS IE9=============");
byte[] data = getBytesFromFile(new File("D:/media/final.mp4"));
String diskfilename = "final.mp4";
response.setContentType("video/mpeg");
//response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename=\"" + diskfilename + "\"" );
System.out.println("data.length " + data.length);
response.setContentLength(data.length);
response.setHeader("Content-Range", range + Integer.valueOf(data.length-1));
response.setHeader("Accept-Ranges", "text/x-dvi");
response.setHeader("Etag", "W/\"9767057-1323779115364\"");
byte[] content = new byte[1024];
BufferedInputStream is = new BufferedInputStream(new ByteArrayInputStream(data));
OutputStream os = response.getOutputStream();
while (is.read(content) != -1) {
//System.out.println("... write bytes");
os.write(content);
}
is.close();
os.close();
}
else if( browser.indexOf("CoreMedia") != -1) {
System.out.println("============ Safari=============");
byte[] data = getBytesFromFile(new File("D:/media/final.mp4"));
String diskfilename = "final.mp4";
response.setContentType("video/mpeg");
//response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition", "attachment; filename=\"" + diskfilename + "\"" );
System.out.println("data.length " + data.length);
//response.setContentLength(data.length);
//response.setHeader("Content-Range", range + Integer.valueOf(data.length-1));
// response.setHeader("Accept-Ranges", " text/*, text/html, text/html;level=1, */* ");
// response.setHeader("Etag", "W/\"9767057-1323779115364\"");
byte[] content = new byte[1024];
BufferedInputStream is = new BufferedInputStream(new ByteArrayInputStream(data));
OutputStream os = response.getOutputStream();
while (is.read(content) != -1) {
//System.out.println("... write bytes");
os.write(content);
}
is.close();
os.close();
}
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
private static byte[] getBytesFromFile(File file) throws IOException {
InputStream is = new FileInputStream(file);
//System.out.println("\nDEBUG: FileInputStream is " + file);
// Get the size of the file
long length = file.length();
//System.out.println("DEBUG: Length of " + file + " is " + length + "\n");
/*
* You cannot create an array using a long type. It needs to be an int
* type. Before converting to an int type, check to ensure that file is
* not loarger than Integer.MAX_VALUE;
*/
if (length > Integer.MAX_VALUE) {
System.out.println("File is too large to process");
return null;
}
// Create the byte array to hold the data
byte[] bytes = new byte[(int)length];
// Read in the bytes
int offset = 0;
int numRead = 0;
while ( (offset < bytes.length)
&&
( (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) ) {
offset += numRead;
}
// Ensure all the bytes have been read in
if (offset < bytes.length) {
throw new IOException("Could not completely read file " + file.getName());
}
is.close();
return bytes;
}
}

Honestly, this approach is absolutely not right.
You are sniffing the user agent in the server side and depending the business job on it. This is in all cases a bad idea. If all you want is to specify a different file depending on the user agent, then rather do it in the HTML side, with help of JavaScript or CSS. Both client side languages are able to identify the real browser without the need to sniff the user agent string (which is namely spoofable).
You are not responding correctly on Range requests. You're sending the complete file back instead of the requested Range. Firefox and IE do not use range requests and that's why it "works". Chrome and Safari use range requests.
This should be possible without sniffing the user agent and properly responding to Range requests by RandomAccessFile instead of File and byte[]. It's only pretty a lot of code to take all HTTP specification requirements into account, so here's just a link where you can find a concrete example of such a servlet: FileServlet supporting resume and caching.
However, much better is to delegate the job to the servletcontainer's default servlet. If it's for example Tomcat, then all you need to do is to add the following line to /conf/server.xml:
<Context docBase="D:\media" path="/media" />
This way the desired media files are just available by http://localhost:8080/media/final.ogg and http://localhost:8080/media/final.mp4 without the need to homegrow a servlet.

This seems to be more of a format support issue.
You can try ogg format. The HTML5 code is
<audio controls="controls">
  <source src="song.ogg" type="audio/ogg" />
  Your browser does not support the audio tag.
</audio>

Google Chrome does not support H.264 (includes mp4) so you need to use final.ogg with google chrome as well. while for safari you need to change this line
browser.indexOf("CoreMedia") != -1
add "Safari" instead of "CoreMedia"
i hope it works.

String diskfilename = "final.mp4";
response.setHeader("Content-Disposition", "attachment; filename=\"" + diskfilename + "\"" );
Just comment these two lines and then run on chrome your video will play.

Related

How to download/export .txt file in java?

I formed an url in the controller.When I hit that url i need to export a .txt file.As I am new to this concept , I have a doubts ,
1) Do we need to import any jar file to export .txt file as like we add jars for pdf and xls ?
I have tried like below..But i dont get any result by it.I didn't add any jar file ..
FileWriter writer = new FileWriter("MyFile.txt", true);
writer.write("Hello World");
writer.write("\r\n"); // write new line
writer.write("Good Bye!");
writer.close();
In a couple of projects I've used this utility class from codejava.net
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
/**
* A utility that downloads a file from a URL.
* #author www.codejava.net
*
*/
public class HttpDownloadUtility {
private static final int BUFFER_SIZE = 4096;
/**
* Downloads a file from a URL
* #param fileURL HTTP URL of the file to be downloaded
* #param saveDir path of the directory to save the file
* #throws IOException
*/
public static void downloadFile(String fileURL, String saveDir)
throws IOException {
URL url = new URL(fileURL);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
int responseCode = httpConn.getResponseCode();
// always check HTTP response code first
if (responseCode == HttpURLConnection.HTTP_OK) {
String fileName = "";
String disposition = httpConn.getHeaderField("Content-Disposition");
String contentType = httpConn.getContentType();
int contentLength = httpConn.getContentLength();
if (disposition != null) {
// extracts file name from header field
int index = disposition.indexOf("filename=");
if (index > 0) {
fileName = disposition.substring(index + 10,
disposition.length() - 1);
}
} else {
// extracts file name from URL
fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1,
fileURL.length());
}
System.out.println("Content-Type = " + contentType);
System.out.println("Content-Disposition = " + disposition);
System.out.println("Content-Length = " + contentLength);
System.out.println("fileName = " + fileName);
// opens input stream from the HTTP connection
InputStream inputStream = httpConn.getInputStream();
String saveFilePath = saveDir + File.separator + fileName;
// opens an output stream to save into file
FileOutputStream outputStream = new FileOutputStream(saveFilePath);
int bytesRead = -1;
byte[] buffer = new byte[BUFFER_SIZE];
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
System.out.println("File downloaded");
} else {
System.out.println("No file to download. Server replied HTTP code: " + responseCode);
}
httpConn.disconnect();
}
}
The code i have written is just a three lines to download the .txt file.
Thank you all For the help.
I am just posting my answer because just to download a empty file who need for the beginners.
Adding HttpServletResponse servletResponse dependency,
OutputStream out = servletResponse.getOutputStream();
String headerKey = "Content-Disposition";
String headerValue = String.format("attachment; filename=\"Report"+".txt\";");
servletResponse.setHeader(headerKey, headerValue);
// obtains response's output stream
OutputStream outStream = servletResponse.getOutputStream();
outStream.close();

Socket programming - write() fixed number of bytes from Java Servlet to server C

need some help reading the exact bytes from my java client side to C server. STREAM. I would like to read, lets say, the first two bytes then know which (string/Total No of bytes) are being sent thus use my recv_exactly() function which will take in the actual number of bytes as an argument. This is so that I can limit the wait time instead of reading all 1024 expected buffer size. AND also, any ideas how i can send a struct from the java side to make this neat.
Thanks a bunch!
//*************** Java Client *****************
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException{
sslsocket.startHandshake();
kmipoutstream = sslsocket.getOutputStream();
OutputStreamWriter outputstreamwriter = new OutputStreamWriter(kmipoutstream);
// figure out what we want to ask for
final String path = request.getPathInfo();
System.out.println("request pathInfo: " + path);
if (path == null || path.endsWith("/users")) {
//***********SHOULD I SEND 13 FIRST = 2 BYTES?? ***************
outputstreamwriter.write("13")
outputstreamwriter.write("GET ALL USERS");
} else if (path.endsWith("/keys")) {
outputstreamwriter.write("GET ALL KEYS");
} else if (path.endsWith("/templates")) {
outputstreamwriter.write("GET ALL TEMPLATES");}
outputstreamwriter.flush();
BufferedReader wireBufReader = new BufferedReader(
new InputStreamReader(sslsocket.getInputStream()));
String tmp = wireBufReader.readLine();
System.out.println(tmp);
int numrows = Integer.parseInt(tmp);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.setHeader("Cache-control", "max-age=0");
response.setHeader("Content-Range", "0-" + numrows + "/" + numrows);
while (!(tmp = wireBufReader.readLine()).isEmpty()) {
response.getOutputStream().println(tmp);}
kmipoutstream.close();
}
//********** Server.C *******************
inBuf = calloc(1, 1024);
if (inBuf == NULL){
debug_print("ERROR: Memory allocation for inbuf.\n", NULL);
endProcessing = 1;}
printf("This is inBuf= %s \n", *inBuf);
while (!endProcessing){
sts = RS_SUCCESS;
do{
//do accept, followed by negotiate
sts = rs_ssl_negotiate_viaAccept(rs_ssl_env, IOMODE_NONBLOCKING,
listenerSocket, &rs_ssl_conn, &ssllog);
printf("After negotiate and accept sts = %d\n", sts);
if (RS_SUCCESS != sts){
debug_print("ERROR: Error during accept and negotiate: %d\n", sts);
rslog_print(ssllog);
break;
/*
* receive the get request, parse it out, and call the db method.
*/
//memset(inBuf, 0, 1024);
//*******I NEED HELP HERE. NOT SURE HOW TO KNOW THE EXACT NUMBER OF
BYTES BEING SENT BEFORE I CALL
RS_SSL_RECV_EXACTLY ********************
if( = rs_ssl_recv_exactly(rs_ssl_conn, inBuf, 2, &ssllog)){
debug_print("ERROR: During HTTP receive: %d\n", sts);
rslog_print(ssllog);
break; }
else
{ if (sts = db_get_userlist_json(jInfo->db_ctx, &jsonBuf, &numrows))
{debug_print("error getting json user: %d\n", sts);
break;}}
__atoe_l(inBuf, actualBytes);
debug_print("successfully received %d bytes of request:\n<%s>\n", bytesRecvd, inBuf);
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException{
sslsocket.startHandshake();
kmipoutstream = sslsocket.getOutputStream();
OutputStreamWriter outputstreamwriter = new OutputStreamWriter(kmipoutstream);
// figure out what we want to ask for
final String path = request.getPathInfo();
System.out.println("request pathInfo: " + path);
if (path == null || path.endsWith("/users")) {
// ******** SHOULD I SEND 13 FIRST = 2 BYTES?? ***********
outputstreamwriter.write("13");
outputstreamwriter.write("GET ALL USERS");
} else if (path.endsWith("/keys")) {
outputstreamwriter.write("GET ALL KEYS");
} else if (path.endsWith("/templates")) {
outputstreamwriter.write("GET ALL TEMPLATES");
}
outputstreamwriter.flush();
BufferedReader wireBufReader = new BufferedReader(
new InputStreamReader(sslsocket.getInputStream()));
String tmp = wireBufReader.readLine();
System.out.println(tmp);
int numrows = Integer.parseInt(tmp);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.setHeader("Cache-control", "max-age=0");
response.setHeader("Content-Range", "0-" + numrows + "/" + numrows);
while (!(tmp = wireBufReader.readLine()).isEmpty()) {
response.getOutputStream().println(tmp);
}
kmipoutstream.close();
}
This is so that I can limit the wait time instead of reading all 1024 expected buffer size.
But recv() doesn't behave like that. It blocks until at least one byte is available (in blocking mode), then transfers whatever is available, up to the specified length. It makes no attempt to fill the buffer, unless that much data happens to be available.
So your problem doesn't exist in the first place.

IE8 asks to Open/Save twice on .xls file

I'm generating an Excel document via Servlet. When I send the response back to the client (IE8), the "Open/Save" dialog pops up but requires users to click a choice twice before taking action. This doesn't happen in Firefox. I have no idea why this is occurring. Below is the relevant code that creates the appropriate streams.
result contains the Excel XML.
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment;filename=TestFile.xls");
InputStream in = new ByteArrayInputStream(result.toString().getBytes("UTF-8"));
ServletOutputStream out = response.getOutputStream();
try
{
byte[] outputByte = new byte[4096];
while(in.read(outputByte, 0, 4096) != -1)
out.write(outputByte, 0, 4096);
}
finally
{
in.close();
out.flush();
out.close();
}
EDIT
I have noticed that waiting 5+ seconds before clicking an option works just fine. It seems to only ask twice when immediately clicking an option.
This code works well for every type of file in my application
InputStream in = blob.getBinaryStream();
// Output the blob to the HttpServletResponse
String codedfilename = "";
//this code resolves the issue with the encoding of the downloaded filename
String agent = request.getHeader("USER-AGENT");
if (null != agent && -1 != agent.indexOf("MSIE"))
{
codedfilename = URLEncoder.encode(/*here goes the filename*/, "UTF8");
response.setContentType("application/x-download");
response.setHeader("Content-Disposition","attachment;filename=" + codedfilename);
}
else if (null != agent && -1 != agent.indexOf("Mozilla"))
{
response.setCharacterEncoding("UTF-8");
//It does not seem to make a difference whether Q or B is chosen
codedfilename = MimeUtility.encodeText(rset.getString("FILE_NAME"), "UTF8", "B");
response.setContentType("application/force-download");
response.addHeader("Content-Disposition", "attachment; filename=\"" + codedfilename + "\"");
}
BufferedOutputStream out =
new BufferedOutputStream(response.getOutputStream());
byte by[] = new byte[32768];
int index = in.read(by, 0, 32768);
while (index != -1) {
out.write(by, 0, index);
index = in.read(by, 0, 32768);
}
out.flush();
try it and let us know

Download a file through an HTTP Get in java

I've written a download Servlet to return a file based on a messageID parameter. Below is the doGet method.
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// This messageID would be used to get the correct file eventually
long messageID = Long.parseLong(request.getParameter("messageID"));
String fileName = "C:\\Users\\Soto\\Desktop\\new_audio1.amr";
File returnFile = new File(fileName);
ServletOutputStream out = response.getOutputStream();
ServletContext context = getServletConfig().getServletContext();
String mimetype = context.getMimeType("C:\\Users\\Soto\\Desktop\\new_audio1.amr");
response.setContentType((mimetype != null) ? mimetype : "application/octet-stream");
response.setContentLength((int)returnFile.length());
response.setHeader("Content-Disposition", "attachment; filename=\"" + "new_audio.amr" + "\"");
FileInputStream in = new FileInputStream(returnFile);
byte[] buffer = new byte[4096];
int length;
while((length = in.read(buffer)) > 0) {
out.write(buffer, 0, length);
}
in.close();
out.flush();
}
I then wrote some code to retrieve the file.
String url = "http://localhost:8080/AudioFileUpload/DownloadServlet";
String charset = "UTF-8";
// The id of the audio message requested
String messageID = "1";
//URLConnection connection = null;
try {
String query = String.format("messageID=%s", URLEncoder.encode(messageID, charset));
//URLConnection connection;
//URL u = new URL(url + "?" + query);
//connection = u.openConnection();
//InputStream in = connection.getInputStream();
HttpClient httpClient = new DefaultHttpClient();
httpClient.getParams().setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1);
HttpGet httpGet = new HttpGet(url + "?" + query);
HttpResponse response = httpClient.execute(httpGet);
System.out.println(response.getStatusLine());
InputStream in = response.getEntity().getContent();
FileOutputStream fos = new FileOutputStream(new File("C:\\Users\\Soto\\Desktop\\new_audio2.amr"));
byte[] buffer = new byte[4096];
int length;
while((length = in.read(buffer)) > 0) {
fos.write(buffer, 0, length);
}
//connection = new URL(url + "?" + query).openConnection();
//connection.setRequestProperty("Accept-Charset", charset);
//InputStream response = connection.getInputStream();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Now this code works fine. I can download the audio file and it works correctly. What I want to know is how to, if possible, get the name of the file as it is downloaded instead of giving it my own name. Also, is it possible to get the file without having to read from the stream (maybe some library that does it for you)? I kind of want to hide the dirty stuff.
Thanks
For setting the download file name do the following on response object in Servlet code
response.setHeader("Content-disposition",
"attachment; filename=" +
"new_audio1.amr" );
EDIT:
I see you are already doing it. Just try removing the slashes you have added.
With attachment, the file will be served with the provided name properly. When inline, browsers seem to ignore filename, and usually give the servletname part of the URL as default name when saving the inline contents.
You could try mapping that URL to an appropriate filename, if that is suitable.
Here's a SO related question: Securly download file inside browser with correct filename
You may also find this link useful: Filename attribute for Inline Content-Disposition Meaningless?
I think you cannot download file without streaming. For I/O you must use stream.

file upload using java servlet as a service without a web browser

I am very new to java and servlet programming.
I am not sure whether it is possible to write a servlet which when passed a URL from the local client machine, uploads the file to the server.
basically on the client machine we have a C# program and on the server side we have Apache-tomcat installed. I need to upload file(s) to the server using C# program on client machine.
Should I provide any more information (?)
Thanks in Advance
Note this code illustrates the general idea and not guaranteed to work without modification.
The C# file upload part
// this code shows you how the browsers wrap the file upload request, you still can fine a way simpler code to do the same thing.
public void PostMultipleFiles(string url, string[] files)
{
string boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x");
HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
httpWebRequest.ContentType = "multipart/form-data; boundary=" + boundary;
httpWebRequest.Method = "POST";
httpWebRequest.KeepAlive = true;
httpWebRequest.Credentials = System.Net.CredentialCache.DefaultCredentials;
Stream memStream = new System.IO.MemoryStream();
byte[] boundarybytes =System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary +"\r\n");
string formdataTemplate = "\r\n--" + boundary + "\r\nContent-Disposition: form-data; name=\"{0}\";\r\n\r\n{1}";
string headerTemplate = "Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"\r\n Content-Type: application/octet-stream\r\n\r\n";
memStream.Write(boundarybytes, 0, boundarybytes.Length);
for (int i = 0; i < files.Length; i++)
{
string header = string.Format(headerTemplate, "file" + i, files[i]);
//string header = string.Format(headerTemplate, "uplTheFile", files[i]);
byte[] headerbytes = System.Text.Encoding.UTF8.GetBytes(header);
memStream.Write(headerbytes, 0, headerbytes.Length);
FileStream fileStream = new FileStream(files[i], FileMode.Open,
FileAccess.Read);
byte[] buffer = new byte[1024];
int bytesRead = 0;
while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) != 0)
{
memStream.Write(buffer, 0, bytesRead);
}
memStream.Write(boundarybytes, 0, boundarybytes.Length);
fileStream.Close();
}
httpWebRequest.ContentLength = memStream.Length;
Stream requestStream = httpWebRequest.GetRequestStream();
memStream.Position = 0;
byte[] tempBuffer = new byte[memStream.Length];
memStream.Read(tempBuffer, 0, tempBuffer.Length);
memStream.Close();
requestStream.Write(tempBuffer, 0, tempBuffer.Length);
requestStream.Close();
try
{
WebResponse webResponse = httpWebRequest.GetResponse();
Stream stream = webResponse.GetResponseStream();
StreamReader reader = new StreamReader(stream);
string var = reader.ReadToEnd();
}
catch (Exception ex)
{
response.InnerHtml = ex.Message;
}
httpWebRequest = null;
}
and to understand how the above code was written you might wanna take a look at How does HTTP file upload work?
POST /upload?upload_progress_id=12344 HTTP/1.1
Host: localhost:3000
Content-Length: 1325
Origin: http://localhost:3000
... other headers ...
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryePkpFF7tjBAqx29L
------WebKitFormBoundaryePkpFF7tjBAqx29L
Content-Disposition: form-data; name="MAX_FILE_SIZE"
100000
------WebKitFormBoundaryePkpFF7tjBAqx29L
Content-Disposition: form-data; name="uploadedfile"; filename="hello.o"
Content-Type: application/x-object
... contents of file goes here ...
------WebKitFormBoundaryePkpFF7tjBAqx29L--
and finally all you have to do is to implement a servlet that can handle the file upload request, then you do whatever that you want to do with the file, take a look at this file upload tutorial
protected void processRequest(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
// Create path components to save the file
final String path = request.getParameter("destination");
final Part filePart = request.getPart("file");
final String fileName = getFileName(filePart);
OutputStream out = null;
InputStream filecontent = null;
final PrintWriter writer = response.getWriter();
try {
out = new FileOutputStream(new File(path + File.separator
+ fileName));
filecontent = filePart.getInputStream();
int read = 0;
final byte[] bytes = new byte[1024];
while ((read = filecontent.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
writer.println("New file " + fileName + " created at " + path);
LOGGER.log(Level.INFO, "File{0}being uploaded to {1}",
new Object[]{fileName, path});
} catch (FileNotFoundException fne) {
writer.println("You either did not specify a file to upload or are "
+ "trying to upload a file to a protected or nonexistent "
+ "location.");
writer.println("<br/> ERROR: " + fne.getMessage());
LOGGER.log(Level.SEVERE, "Problems during file upload. Error: {0}",
new Object[]{fne.getMessage()});
} finally {
if (out != null) {
out.close();
}
if (filecontent != null) {
filecontent.close();
}
if (writer != null) {
writer.close();
}
}
}
private String getFileName(final Part part) {
final String partHeader = part.getHeader("content-disposition");
LOGGER.log(Level.INFO, "Part Header = {0}", partHeader);
for (String content : part.getHeader("content-disposition").split(";")) {
if (content.trim().startsWith("filename")) {
return content.substring(
content.indexOf('=') + 1).trim().replace("\"", "");
}
}
return null;
}

Categories

Resources