1

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);
       }
   }
}
martoncsukas
  • 2,077
  • 20
  • 23
AabinGunz
  • 12,109
  • 54
  • 146
  • 218
  • Check this link:http://stackoverflow.com/questions/2646194/multipart-file-upload-post-request-from-java?rq=1 – pd30 Sep 23 '14 at 13:26

4 Answers4

0

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());
}
}
ajitksharma
  • 4,523
  • 2
  • 21
  • 40
  • It is not able to upload a 6MB file gives me this exception `post length6402546 Sep 18, 2014 8:23:53 PM org.apache.http.impl.client.DefaultHttpClient tryExecute INFO: I/O exception (java.net.SocketException) caught when processing request to {}->http://localhost:4060: Connection reset by peer: socket write error` – AabinGunz Sep 18 '14 at 14:56
  • its a IO Exception, check your URL, as mentioned by you [b]request to {}->http://localhost:4060:[b] is server homepage, you should have some valid URL of your service – ajitksharma Sep 19 '14 at 03:34
  • I am able to upload small sized files with the same url and ur code too, but the problem exists with uploading large files. I have edited just the url part in the comment, actual url is appended by a /servlet name. – AabinGunz Sep 19 '14 at 03:38
  • 1
    @abi1964 That error is saying that the peer (server) reset the connection, if it's only occurring on larger files then your server has a filesize or timeout limit. – Robadob Sep 24 '14 at 12:32
0

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.

Rostislav Matl
  • 4,294
  • 4
  • 29
  • 53
  • HTTP server is a netty server deployed by a program so not sure if that's an issue. I used a curl command `curl --form "fileupload=@small.xml" https://localhost:8080/servlet` which is able to upload small files. Is this **curl** command correct for uploading large files? Also there is enough memory and disk size available. – AabinGunz Sep 22 '14 at 03:47
  • I suppose there is no artificial limit in curl but I do not know it for sure. – Rostislav Matl Sep 30 '14 at 09:51
  • have you manged to overcome the problem ? What was the cause ? – Rostislav Matl Nov 17 '14 at 12:30
  • Yes, it was a server side issue. Thanks – AabinGunz Nov 19 '14 at 16:36
0

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.

martoncsukas
  • 2,077
  • 20
  • 23
Kandy
  • 1,067
  • 12
  • 29
0

Refer here

We can upload any number of files of any sizes using plupload.

Community
  • 1
  • 1
Ashutosh Jha
  • 1,465
  • 1
  • 17
  • 28