2

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);
       }
   }
}
1

4 Answers 4

1

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.

Sign up to request clarification or add additional context in comments.

Comments

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.

4 Comments

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 "[email protected]" 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.
I suppose there is no artificial limit in curl but I do not know it for sure.
have you manged to overcome the problem ? What was the cause ?
Yes, it was a server side issue. Thanks
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());
}
}

4 Comments

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
its a IO Exception, check your URL, as mentioned by you [b]request to {}->localhost:4060:[b] is server homepage, you should have some valid URL of your service
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.
@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.
0

Refer here

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.