Getting the string values of an enum - java

I want to make a program that downloads some files that are needed to run a gain. It's like a launcher that automatically downloads updates. This is the enum I have:
public class Configuration {
public enum downloadFiles {
load1 ("load1.png", "https://dl.dropboxusercontent.com/u/51947680/Xenolith/load1.png"),
load2 ("load2.png", "https://dl.dropboxusercontent.com/u/51947680/Xenolith/load2.png"),
load3 ("load3.png", "https://dl.dropboxusercontent.com/u/51947680/Xenolith/load3.png");
public String fileName, URL;
private downloadFiles(String fileName, String URL) {
this.fileName = fileName;
this.URL = URL;
}
public String getFileName() {
return fileName;
}
public String getURL() {
return URL;
}
}
}
I also have a class that downloads the files, which is:
public class DownloadUtility {
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 fileName, String fileURL)
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 disposition = httpConn.getHeaderField("Content-Disposition");
String contentType = httpConn.getContentType();
int contentLength = httpConn.getContentLength();
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 = System.getProperty("user.home") + "/Desktop" + 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();
}
}
So what I want to do is that the downloadFiles method downloads all the files in the enum sequentially. Btw is this a good way of doing this? If there is a better way, can you please tell me, because I'm trying to learn to code java in a neat way.

You can do the following:
for(Configuration.downloadFiles df : Configuration.downloadFiles.values()){
DownloadUtility.downloadFile(df.getFileName(), df.getURL());
}

Related

How do I put an inputstream progressmonitor in my code?

I'm trying to put the progressmonitor inputstream in my code, but everything I've done I can't. I'm very new to java programming and have some difficulties implementing certain things in my code.
Apart from this inability to use inputstream, the code works correctly the way I need it. So I would like to see the download progress as it has the exceptions in case the download fails or server down.
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package javatar.language.download;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import javax.swing.JOptionPane;
/**
*
* #author Bruno
*/
public class UrlInput {
public static void main(String[] args) {
String userSys = System.getenv("USERNAME");
String sysDrive = System.getenv("SYSTEMDRIVE");
String downPath = sysDrive + "/Users/" + userSys + "/Downloads";
try {
URL url = new URL("http://akamai-gamecdn.blackdesertonline.com/live001/game/config/config.language.version");
try ( // read text returned by server
BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()))) {
String line;
while ((line = in.readLine()) != null) {
String versao = line;
JOptionPane.showMessageDialog(null, "Actual version BDO-NA: " + versao);
String fileURL = "http://akamai-gamecdn.blackdesertonline.com/live001/game/language/BDOLanguage_" + versao + ".zip";
String saveDIR = downPath;
SysDownload.downloadFile(fileURL, saveDIR);
}
}
} catch (MalformedURLException e) {
JOptionPane.showMessageDialog(null, "Malformed URL: " + e.getMessage());
} catch (IOException e) {
JOptionPane.showMessageDialog(null, "Error I/O: " + e.getMessage());
}
}
}
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package javatar.language.download;
import java.io.*;
import java.net.*;
import javax.swing.*;
/**
*
* #author Bruno
*/
public class SysDownload {
private static final int BUFFER_SIZE = 4096;
public static void downloadFile(String fileURL, String saveDIR) throws IOException {
URL link = new URL(fileURL);
HttpURLConnection conn = (HttpURLConnection) link.openConnection();
int responseCode = conn.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
String fileName = "";
String server = conn.getHeaderField("Server");
String connectionType = conn.getContentType();
int contentLenght = conn.getContentLength();
JOptionPane.showMessageDialog(null, "Server name: " + server);
if (server != null) {
int index = server.indexOf("filename");
if (index > 0) {
fileName = server.substring(index + 10, server.length() - 1);
} else {
fileName = fileURL.substring(fileURL.lastIndexOf("/") + 1, fileURL.length());
}
try (InputStream inputStream = conn.getInputStream()) {
String savePath = saveDIR + File.separator + fileName;
try (FileOutputStream outputStream = new FileOutputStream(savePath)) {
int bytesRead = - 1;
byte[] buffer = new byte[BUFFER_SIZE];
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
}
}
JOptionPane.showMessageDialog(null, "File " + fileName + " has been downloaded.\nSee users Download folder.");
} else {
JOptionPane.showMessageDialog(null, "None file downloaded.\nServer HTTP code: " + responseCode + JOptionPane.ERROR_MESSAGE);
}
conn.disconnect();
}
}
}
First, consult the documentation of ProgressMonitorInputStream.
The constructor requires three arguments. Like JOptionPane, the first argument is the dialog parent, which appers to be null in your application.
The second argument is the message. In your case, "Downloading " + link is probably sufficient.
The third argument is the InputStream to monitor. This should be the InputStream from which you are downloading.
The ProgressMonitor’s maximum should be the size of the download, which you can obtain from the getContentLength() method of URLConnection.
You don’t need to write your loop to save an InputStream to a file. You can use Files.copy for that.
So, putting it all together, it looks like this:
try (ProgressMonitorInputStream inputStream =
new ProgressMonitorInputStream(null,
"Downloading " + link,
conn.getInputStream())) {
inputStream.getProgressMonitor().setMaximum(conn.getContentLength());
Files.copy(inputStream, Paths.get(savePath));
}

How to post ByteArrayOutputStream via http

I am currently reading a file from then writing it to an HTTP connection which saves the file locally to disk - it's working fine.
However, because of the environment I'm working within I cannot read files from disk, rather they are pulled from a database and stored in a ByteArrayOutputStream in my java code.
So instead of starting by reading a file from disk, I need to use a ByteOutputArrayStream and write that to an http connection instead.
I need an efficient method to do this - If I can modify my current code (bloew) that's fine - I'm willing to scrap it all if necessary...
// This is the primary call from jsp
public String postServer(String[] args)throws Exception{
System.out.println("******* HTTPTestJPO inside postServer");
String requestURL = "http://MyServer:8080/TransferTest/UploadServlet";
String charset = "UTF-8";
String sTest=args[0];
String sResponse="";
System.out.println("******* HTTPTestJPO incoming file string sTest:"+sTest);
MultipartUtility multipart = new MultipartUtility(requestURL, charset);
StringTokenizer inFiles=new StringTokenizer(sTest,",");
while(inFiles.hasMoreTokens()){
String tmpFileName=inFiles.nextToken();
System.out.println("******* tokenized tmpFileName:"+tmpFileName);
File uploadFile1 = new File(tmpFileName);
try {
multipart.addFilePart("fileUpload", uploadFile1);
} catch (IOException ex) {
System.err.println("******* HTTPTestJPO EXCEPTION: "+ex);
}
}
sResponse = multipart.handleFinish();
System.out.println("******* HTTPTestJPO SERVER REPLIED:"+sResponse);
return sResponse;
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Multipart utility
////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/**
* This utility class provides an abstraction layer for sending multipart HTTP
* POST requests to a web server.
* #author www.codejava.net
*
*/
public class MultipartUtility {
private final String boundary;
private static final String LINE_FEED = "\r\n";
private HttpURLConnection httpConn;
private String charset;
private OutputStream outputStream;
private PrintWriter writer;
/**
* This constructor initializes a new HTTP POST request with content type
* is set to multipart/form-data
* #param requestURL
* #param charset
* #throws IOException
*/
public MultipartUtility(String requestURL, String charset)throws IOException {
this.charset = charset;
// creates a unique boundary based on time stamp
boundary = "===" + System.currentTimeMillis() + "===";
URL url = new URL(requestURL);
httpConn = (HttpURLConnection) url.openConnection();
httpConn.setUseCaches(false);
httpConn.setDoOutput(true); // indicates POST method
httpConn.setDoInput(true);
httpConn.setRequestProperty("Content-Type","multipart/form-data; boundary=" + boundary);
//httpConn.setRequestProperty("User-Agent", "CodeJava Agent");
//httpConn.setRequestProperty("Test", "Bonjour");
outputStream = httpConn.getOutputStream();
writer = new PrintWriter(new OutputStreamWriter(outputStream, charset),true);
}
/**
* Adds a upload file section to the request
* #param fieldName name attribute in <input type="file" name="..." />
* #param uploadFile a File to be uploaded
* #throws IOException
*/
public void addFilePart(String fieldName, File uploadFile)throws IOException {
String fileName = uploadFile.getName();
writer.append("--" + boundary).append(LINE_FEED);
writer.append("Content-Disposition: form-data; name=\"" + fieldName + "\"; filename=\"" + fileName + "\"").append(LINE_FEED);
writer.append("Content-Type: "+ URLConnection.guessContentTypeFromName(fileName)).append(LINE_FEED);
writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
writer.append(LINE_FEED);
writer.flush();
// HOW CAN I MODIFY THIS TO SEND AN EXISTING BYTEARRAYOUTPUTSTREAM INSTEAD OF A DISK FILE??
FileInputStream inputStream = new FileInputStream(uploadFile);
byte[] buffer = new byte[4096];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.flush();
inputStream.close();
writer.append(LINE_FEED);
writer.flush();
}
/**
* Completes the request and receives response from the server.
* #return a list of Strings as response in case the server returned
* status OK, otherwise an exception is thrown.
* #throws IOException
*/
private String handleFinish() throws IOException {
String sResponse = "";
//close out the multipart send
writer.append(LINE_FEED).flush();
writer.append("--" + boundary + "--").append(LINE_FEED);
writer.close();
// checks server's status code first
int status = httpConn.getResponseCode();
sResponse=Integer.toString(status);
System.out.println("******* HTTPTestJPO http response code:"+status);
// if (status == HttpURLConnection.HTTP_OK) {
// BufferedReader reader = new BufferedReader(new InputStreamReader(
// httpConn.getInputStream()));
// String line = reader.readLine();
// while ((line = reader.readLine()) != null) {
// sResponse+=line;
// }
// reader.close();
httpConn.disconnect();
// } else {
// throw new IOException("Server returned non-OK status: " + status);
// }
return sResponse;
}
}
}
The contents of a ByteArrayOutputStream can be written to another OutputStream using the writeTo method, like this:
byteArrayOutputStream.writeTo(outputStream);
Another option would be to create a new InputStream:
InputStream inputStream = new ByteArrayInputStream(
byteArrayOutputStream.toByteArray());
but calling toByteArray makes a copy of the byte array, so is more expensive.

map file directory from a java server to local machine

I have created a java server application which will take GET requests and return files to the browser. Also the files are downloaded to the directory using "content-disposition:attachment" in header.But this only downloads as files, I want to download as a folder and map it to a local directory. for example
localhost:8080/xyz.jpg gives u an image .But localhost:8080/src/xyz.jpg should be downlaoded as src folder with an image in it eg: downloads/src/xyz.jpg. Currently if i do that ,it downloads as just a file. Since you guys asked.Here is the example code i used :) .thanks
import java.io.*;
import java.net.*;
import java.util.*;
public class myHTTPServer extends Thread {
static final String HTML_START =
"<html>" +
"<title>HTTP Server in java</title>" +
"<body>";
static final String HTML_END =
"</body>" +
"</html>";
Socket connectedClient = null;
BufferedReader inFromClient = null;
DataOutputStream outToClient = null;
public myHTTPServer(Socket client) {
connectedClient = client;
}
public void run() {
try {
System.out.println( "The Client "+
connectedClient.getInetAddress() + ":" + connectedClient.getPort() + " is connected");
inFromClient = new BufferedReader(new InputStreamReader (connectedClient.getInputStream()));
outToClient = new DataOutputStream(connectedClient.getOutputStream());
String requestString = inFromClient.readLine();
String headerLine = requestString;
StringTokenizer tokenizer = new StringTokenizer(headerLine);
String httpMethod = tokenizer.nextToken();
String httpQueryString = tokenizer.nextToken();
StringBuffer responseBuffer = new StringBuffer();
responseBuffer.append("<b> This is the HTTP Server Home Page.... </b><BR>");
responseBuffer.append("The HTTP Client request is ....<BR>");
System.out.println("The HTTP request string is ....");
while (inFromClient.ready())
{
// Read the HTTP complete HTTP Query
responseBuffer.append(requestString + "<BR>");
System.out.println(requestString);
requestString = inFromClient.readLine();
}
if (httpMethod.equals("GET")) {
if (httpQueryString.equals("/")) {
// The default home page
sendResponse(200, responseBuffer.toString(), false);
} else {
//This is interpreted as a file name
String fileName = httpQueryString.replaceFirst("/", "");
fileName = URLDecoder.decode(fileName);
if (new File(fileName).isFile()){
sendResponse(200, fileName, true);
}
else {
sendResponse(404, "<b>The Requested resource not found ...." +
"Usage: http://127.0.0.1:5000 or http://127.0.0.1:5000/</b>", false);
}
}
}
else sendResponse(404, "<b>The Requested resource not found ...." +
"Usage: http://127.0.0.1:5000 or http://127.0.0.1:5000/</b>", false);
} catch (Exception e) {
e.printStackTrace();
}
}
public void sendResponse (int statusCode, String responseString, boolean isFile) throws Exception {
String statusLine = null;
String serverdetails = "Server: Java HTTPServer";
String contentLengthLine = null;
String fileName = null;
String contentTypeLine = "Content-Type: text/html" + "\r\n";
String Content_disposition="Content-Disposition: attachment; filename='src/fname.ext'";
FileInputStream fin = null;
if (statusCode == 200)
statusLine = "HTTP/1.1 200 OK" + "\r\n";
else
statusLine = "HTTP/1.1 404 Not Found" + "\r\n";
if (isFile) {
fileName = responseString;
fin = new FileInputStream(fileName);
contentLengthLine = "Content-Length: " + Integer.toString(fin.available()) + "\r\n";
if (!fileName.endsWith(".htm") && !fileName.endsWith(".html"))
contentTypeLine = "Content-Type: \r\n";
}
else {
responseString = myHTTPServer.HTML_START + responseString + myHTTPServer.HTML_END;
contentLengthLine = "Content-Length: " + responseString.length() + "\r\n";
}
outToClient.writeBytes(statusLine);
outToClient.writeBytes(serverdetails);
outToClient.writeBytes(contentTypeLine);
outToClient.writeBytes(contentLengthLine);
outToClient.writeBytes(Content_disposition);
outToClient.writeBytes("Connection: close\r\n");
outToClient.writeBytes("\r\n");
if (isFile) sendFile(fin, outToClient);
else outToClient.writeBytes(responseString);
outToClient.close();
}
public void sendFile (FileInputStream fin, DataOutputStream out) throws Exception {
byte[] buffer = new byte[1024] ;
int bytesRead;
while ((bytesRead = fin.read(buffer)) != -1 ) {
out.write(buffer, 0, bytesRead);
}
fin.close();
}
public static void main (String args[]) throws Exception {
ServerSocket Server = new ServerSocket (5000, 10, InetAddress.getByName("127.0.0.1"));
System.out.println ("TCPServer Waiting for client on port 5000");
while(true) {
Socket connected = Server.accept();
(new myHTTPServer(connected)).start();
}
}
}
You can't do this using the HTTP protocol and a normal browser, there is no MIME type for folders. Your browser is able to download only files.
If you want to do this through HTTP:
Option 1: Generate a "zip" file (or some other format that enables you to package a folder tree into a single file) which contains the folder tree and send that to the browser.
Option 2: Develop a custom client program that is able to interpret the response that it gets from the server and create the corresponding folders on the local filesystem.

How to get a file name from response header from HttpURLConnection?

I have Client Server program, Client make a connection to server with its URL and server Reads a file and writes to outputstream and client will get that file and save it in a directory. Problem is I am not getting the filename I am sending in response from Server. Here is my Client Server Code.
Client,
private void receiveFile() throws IOException {
String url11="http://localhost:8080/TestServer/TestServer";
// creates a HTTP connection
URL url = new URL(UPLOAD_URL);
HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();
httpConn.setUseCaches(false);
httpConn.setDoOutput(true);
httpConn.setRequestMethod("POST");
int responseCode = httpConn.getResponseCode();
String ff=httpConn.getHeaderField("filename");
System.out.println("FHeader :"+ff);
File saveFile = new File(SAVE_DIR + ff);
StringBuilder builder = new StringBuilder();
builder.append(httpConn.getResponseCode())
.append(" ")
.append(httpConn.getResponseMessage())
.append("\n");
if (responseCode == HttpURLConnection.HTTP_OK) {
// reads server's response
System.out.println(builder);
InputStream inputStream = httpConn.getInputStream();
// opens an output stream for writing file
FileOutputStream outputStream = new FileOutputStream(saveFile);
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead = -1;
System.out.println("Receiving data...");
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
System.out.println("Data received.");
outputStream.close();
inputStream.close();
} else {
System.out.println("Server returned non-OK code: " + responseCode);
}
}
Server ,
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int BUFF_SIZE = 1024;
byte[] buffer = new byte[BUFF_SIZE];
String filePath = "E:\\Docs\\Next stop is Kurki.MP3";
File fileMp3 = new File(filePath);
if(fileMp3.exists()){
System.out.println("FOUND : ");
} else {
System.out.println("FNF");
}
String fNmae=fileMp3.getName();
FileInputStream fis = new FileInputStream(fileMp3);
response.setContentType("audio/mpeg");
response.setHeader("Content-Disposition", "attachment; filename=\"" + fNmae + "\"");
response.addHeader("fName", fNmae);
response.setContentLength((int) fileMp3.length());
OutputStream os = response.getOutputStream();
try {
int byteRead = 0;
while ((byteRead = fis.read(buffer)) != -1) {
os.write(buffer, 0, byteRead);
}
os.flush();
} catch (Exception excp) {
// downloadComplete = "-1";
excp.printStackTrace();
} finally {
os.close();
fis.close();
}
}
I feel everything is correct in Server side , Can any one help me to sort this. It would be great help . thank you.
Try this in server:
File file = new File("E:\\Docs\\Next stop is Kurki.MP3");
ResponseBuilder response = Response.ok((Object) file);
response.header("Content-Disposition",
"attachment; filename="Next stop is Kurki.MP3");
return response.build();
When client is android :
wv = webView;
wv.setDownloadListener(new DownloadListener() {
public void onDownloadStart(String url, String userAgent,
String contentDisposition, String mimetype,
long contentLength) {
String fileName = URLUtil.guessFileName(url, contentDisposition, mimetype);
DownloadManager.Request request = new DownloadManager.Request(
Uri.parse(url));
request.allowScanningByMediaScanner();
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
request.setDestinationInExternalPublicDir("/YouPath", fileName);
DownloadManager dm = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);
dm.enqueue(request);
}
});
Attention here in client String fileName = URLUtil.guessFileName(url, contentDisposition, mimetype)

How to upload large files by multipart request in Java?

I am using this tutorial to upload large files but it is unable to upload even 300KB of file. Also it does not upload anything other than *.txt or *.log files. Need pointers which can help me upload large files irrespective of filetypes.
Sharing modified code
public class MultipartUtility {
private final String boundary
private static final String LINE_FEED = "\r\n"
private HttpURLConnection httpConn
private String charset
private OutputStream outputStream
private PrintWriter writer
public MultipartUtility(String requestURL, String charset)
throws IOException {
this.charset = charset
// creates a unique boundary based on time stamp
boundary = "===" + System.currentTimeMillis() + "==="
URL url = new URL(requestURL)
httpConn = (HttpURLConnection) url.openConnection()
httpConn.setUseCaches(false)
httpConn.setDoOutput(true) // indicates POST method
httpConn.setDoInput(true)
httpConn.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary)
httpConn.setRequestProperty("User-Agent", "CodeJava Agent")
httpConn.setRequestProperty("Test", "Bonjour")
outputStream = httpConn.getOutputStream()
writer = new PrintWriter(new OutputStreamWriter(outputStream, charset), true)
}
public void addFormField(String name, String value) {
writer.append("--" + boundary).append(LINE_FEED)
writer.append("Content-Disposition: form-data; name=\"" + name + "\"").append(LINE_FEED)
writer.append("Content-Type: text/plain; charset=" + charset).append(LINE_FEED)
writer.append(LINE_FEED)
writer.append(value).append(LINE_FEED)
writer.flush()
}
public void addFilePart(String fieldName, File uploadFile) throws IOException {
String fileName = uploadFile.getName()
writer.append("--" + boundary).append(LINE_FEED)
writer.append("Content-Disposition: form-data; name=\"" + fieldName + "\"; filename=\"" + fileName + "\"").append(LINE_FEED)
writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(fileName)).append(LINE_FEED)
writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED)
writer.append(LINE_FEED)
writer.flush()
FileInputStream inputStream = new FileInputStream(uploadFile)
byte[] buffer = new byte[4096]
int bytesRead = -1
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead)
}
outputStream.flush()
inputStream.close()
writer.append(LINE_FEED)
writer.flush()
}
public void addHeaderField(String name, String value) {
writer.append(name + ": " + value).append(LINE_FEED)
writer.flush()
}
public List<String> finish() throws IOException {
List<String> response = new ArrayList<String>()
writer.append(LINE_FEED).flush()
writer.append("--" + boundary + "--").append(LINE_FEED)
writer.close()
// checks server's status code first
int status = httpConn.getResponseCode() //<- Exception coming in this line java.io.IOException: Error writing to server
if (status == HttpURLConnection.HTTP_OK) {
BufferedReader reader = new BufferedReader(new InputStreamReader(
httpConn.getInputStream()))
String line = null
while ((line = reader.readLine()) != null) {
response.add(line)
}
reader.close()
httpConn.disconnect()
} else {
throw new IOException("Server returned non-OK status: " + status)
}
return response
}
static main(args) {
String charset = "UTF-8";
File uploadFile1 = new File("C:\\1392943434245.xml");
String requestURL = "http://localhost:10060/testme";
try {
MultipartUtility multipart = new MultipartUtility(requestURL, charset);
multipart.addFilePart("fileUpload", uploadFile1);
List<String> response = multipart.finish();
println("SERVER REPLIED:");
for (String line : response) {
System.out.println(line);
}
} catch (IOException ex) {
System.err.println(ex);
}
}
}
Have you checked that your HTTP server does not impose a size limit on requests ?
Is there enough memory and disk size ?
Maybe the cause is not in your code.
Try this code, you can be able to upload any file type
public class TryFile {
public static void main(String[] ar) throws HttpException, IOException, URISyntaxException {
// TODO Auto-generated method stub
TryFile t=new TryFile();
t.method();
}
public void method() throws HttpException, IOException, URISyntaxException
{
String url="<your url>";
String fileName="<your file name>";
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(url);
FileBody fileContent= new FileBody(new File(fileName));
StringBody comment = new StringBody("Filename: " + fileName);
MultipartEntity reqEntity = new MultipartEntity();
reqEntity.addPart("file", fileContent);
httppost.setEntity(reqEntity);
System.out.println("post length"+reqEntity.getContentLength());
HttpResponse response = httpclient.execute(httppost);
HttpEntity resEntity = response.getEntity();
System.out.println("end"+resEntity.getContentLength());
}
}
This is a working code for file upload:
<jsp:useBean id="upBean" scope="session" class="javazoom.upload.UploadBean" >
<jsp:setProperty name="upBean" property="filesizelimit" value="<%= 1024 * 1024%>" />
</jsp:useBean>
try this,
try {
if (MultipartFormDataRequest.isMultipartFormData(request)) {
MultipartFormDataRequest mrequest = new MultipartFormDataRequest(request);
Hashtable files = mrequest.getFiles();
byte data[] = null;
if ((files != null) && (!files.isEmpty())) {
fileObj = (UploadFile) files.get("fileUpload");
m_imagename = fileObj.getFileName().trim();
//File type validator
if (!Utility.isValiedFileName1(m_imagename)) {
ERROR = "Invalid File Type";
response.sendRedirect("XXX.jsp");//response page
return;
}
//file uploader method call
if ((fileObj != null) && (fileObj.getFileName() != null)) {
data = fileObj.getData();
//Java method for uploading
result = imageUpload.copyImage(data);//depCode
}
}
}
} catch (Exception e) {
SystemMessage.getInstance().writeMessage(" ERROR : " + e);
}
This is part related to HTTP.
Refer
here
We can upload any number of files of any sizes using plupload.

Categories