java client using http bulk transfer files to the server

Will report stack overflow exception when these days do a project encountered problems with java swing client to the server do the bulk transfer files, transfer amounted to 200M. Code is as follows:
byte [] Content = null;
            the try {
                FIN = new new the FileInputStream (File);
                ByteArrayOutputStream OUT = new new ByteArrayOutputStream ();
                byte [] TEMP = new new byte [1024];
                int size = 0;
                the while ((size = FIN .read (TEMP)) = -1) {!
                    out.write (TEMP, 0, size);
                }
                fin.close ();
                Content = out.toByteArray ();
            } the catch (Exception E) {
                e.printStackTrace () ;
            }
Bulk upload is a round-robin fashion to an array of content for each file stream sent to the server, the file name is also sent to the server, and then an array of content written to the file. This approach Ben collapse in the virtual machine files larger amount of java.
My solution is to upload http method, is still doing a loop, as follows :( Click the Upload button on the swing interface, perform the following this thread)
Private String ServerAddress;
private static String HTTPHEAD = "http://";
private static String HTTPTAIL = ":8080/wms//ReceiveUploadFile";
private String uploadedfilesforlog = ""; // upload the log file name for the log preservation
Runnable upload = new Runnable() {
public void run() {
File[] files = fileChooser.getSelectedFiles();
            if(files.length>50){
            JOptionPane.showMessageDialog (uploadFileDialog.this, "the number of upload files can not be more than 50");
            uploadButton.setEnabled(true);
return;
            }
StringBuffer uploadedfiles = new StringBuffer();
if (null == files || files.length == 0) {
JOptionPane.showMessageDialog (uploadFileDialog.this, "you do not select voice files, select the audio file uploaded.");
uploadButton.setEnabled(true);
return;
}
serveraddress = dsclient.getServerAddrss();
for (int i = 0; i < files.length; i++) {
String targetURL = null;// TODO 指定URL
File targetFile = null; // TODO specified file upload
targetFile = files[i];
targetURL = HTTPHEAD + serveraddress + HTTPTAIL; // servleturl
PostMethod filePost = new PostMethod(targetURL);
//filePost.getParams().setContentCharset("utf-8");
logger.info(filePost.getParams().getContentCharset());
try {
// page parameters can be simulated by the following method to submit
Part[] parts = { new FilePart(targetFile.getName(),targetFile) };
filePost.setRequestEntity(new MultipartRequestEntity(parts,filePost.getParams()));
HttpClient client = new HttpClient();
client.getHttpConnectionManager().getParams().setConnectionTimeout(5000);
int status = client.executeMethod(filePost);
if (status == HttpStatus.SC_OK) {
if (saveAudioFileToDatabase(files[i]).equals("upload failed")) {
continue;
}
uploadedfilesforlog += uploadedfilesforlog.equals("")?files[i].getName():"," + files[i].getName();
saveLog("success");
logger.info (files [i] .getName () + "successful upload");
uploadedfiles.append("[");
uploadedfiles.append(files[i].getName());
uploadedfiles.append("]");
if ((i + 1) % 5 == 0) {
uploadedfiles.append("<BR>");
}
} else {
logger.info ( "upload failed");
// upload failed
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
filePost.releaseConnection();
}
}
if (uploadedfiles.length() == 0) {
return;
}
uploadButton.setEnabled(true);
String tip = "<html> voice file <font color = 'red'> <b>"+ Uploadedfiles.toString () + "</ b> </ font> successful upload </ html>!";
JOptionPane.showMessageDialog(uploadFileDialog.this, tip);
uploadFileDialog.this.setVisible(false);
uploadFileDialog.this.dispose();
audioFileManagement.loadList();
}
};
服务器短接受代码:
import java.io.File;
import java.io.IOException;
import java.io.PrintStream;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.log4j.Logger;
public class ReceiveUploadFile extends HttpServlet
{
  private static final long serialVersionUID = 1L;
  Logger logger = Logger.getLogger(ReceiveUploadFile.class);
  private String uploadPath = "/var/lib/X1000/sounds/audiofile/";
  private String tempPath = "/var/lib/X1000/sounds/audiofile/buffer/";
  File tempPathFile;
  public void init()
    throws ServletException
  {
    File uploadFile = new File(this.uploadPath);
    if (!(uploadFile.exists()))
      uploadFile.mkdirs();
    File tempPathFile = new File(this.tempPath);
    if (!(tempPathFile.exists()))
      tempPathFile.mkdirs();
  }
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException
  {
    doPost(request, response);
  }
  public void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException
  {
    DiskFileItemFactory factory;
    try
    {
      factory = new DiskFileItemFactory();
      factory.setSizeThreshold(4096);
      factory.setRepository(this.tempPathFile);
      ServletFileUpload upload = new ServletFileUpload(factory);
      upload.setSizeMax(41943040L);
      List items = upload.parseRequest(request);
      Iterator i = items.iterator();
      while (i.hasNext())
      {
        FileItem fi = (FileItem)i.next();
        String fileName = fi.getName();
        if (fileName != null)
        {
          String filename = new String(fi.getName().getBytes(), "utf-8");
          this.logger.info("=======================接收到语音文件的文件名:" + filename);
          File fullFile = new File(filename);
          File savedFile = new File(this.uploadPath, fullFile.getName());
          fi.write(savedFile);
        }
      }
      System.out.print("upload succeed");
    }
    catch (Exception e)
    {
      System.out.println(e.getMessage());
      e.printStackTrace();
    }
  }
}
web.xml
<servlet>
  <servlet-name>ReceiveUploadFile</servlet-name>
  <display-name>ReceiveUploadFile</display-name>
  <description>ReceiveUploadFile</description>
  <servlet-class>com.gohigh.centrex.common.ReceiveUploadFile</servlet-class>
  <load-on-startup>4</load-on-startup>
  </servlet>
-<servlet-mapping>
  <servlet-name>ReceiveUploadFile</servlet-name>
  <url-pattern>/ReceiveUploadFile</url-pattern>
  </servlet-mapping>

Dependent jar package: commons-httpclient-3.1.jar, Commons-FileUpload-1.2.1.jar, Commons-CODEC-1.3.jar,
problems encountered: Chinese garbage problem, because the commons-httpclient-3.1.jar package the default encoding is not UTF-8, it is sent to the server Chinese file name server to resolve garbled. Read a lot of online methods
are set encoding, but I tried, or not, we can only modify the jar package source code. A jar of ready-made package Download utf-8's:

http://download.csdn.net/detail/wcbkanaz/3697109 , thanks to enthusiastic users.
In addition, modify the source code inside when the code are encoded into what you want, so as to ensure that the server can be resolved correctly.
http://download.csdn.net/detail/yuanxw44/4028099 , this address you can download the source code, unzip the files in the directory copying can be inside java, need to rely on two packages src directory under the eclipse,
commons-logging.jar and commons-codec.jar, revised once again playing with fatjar.



commons-httpclient-3.1.jar
commons-fileupload-1.2.1.
commons-fileupload-1.2.1.
commons-codec-1.3.jar
Published 34 original articles · won praise 2 · views 40000 +

Guess you like

Origin blog.csdn.net/zjj2006/article/details/17171521