2011-05-20 69 views

回答

0

使用RandomAccessFile。我相信这已经被覆盖了。

java file input with rewind()/reset() capability

基本上你只寻求切入点,写上你想从那里无论多少字节,并记住你停止从写点。

+0

咦?这完全没有必要。你不需要这样做。顺便提一下,我认为问题是关于客户端而不是服务器端。 – 2011-05-20 16:22:52

+0

@Robin我想OP会做出决定,但我可能误解了这个问题。 – KyleM 2011-05-20 16:30:22

0

您可以简单地将文件分开,使用Socket API发送,然后重新组装文件。

3

*可以使用plupload完成。 这里是示例。 我的index.html是下: -

<!DOCTYPE html> 
    <html> 
    <head> 
    <meta http-equiv="content-type" content="text/html; charset=UTF-8"/> 
    <title>Upload</title> 
    <!-- production --> 
    <script type="text/javascript" src="js/plupload.full.min.js"></script> 
    <!-- debug 
    <script type="text/javascript" src="../js/moxie.js"></script> 
    <script type="text/javascript" src="../js/plupload.dev.js"></script> 
    --> 
    </head> 
    <body style="font: 13px Verdana; background: #eee; color: #333"> 
    <div id="filelist"></div> 
    <br /> 
     <button id="pickfiles" >Select file</button> 
     <button id="uploadfiles" >Upload</button> 
     <div id="container"> 
    </div> 
    <br /> 
    <pre id="console"></pre> 
    <script type="text/javascript"> 
    // Custom example logic 
    var uploader = new plupload.Uploader({ 
     runtimes : 'html5', 
     browse_button : 'pickfiles', // you can pass an id... 
     container: document.getElementById('container'), // ... or DOM Element itself 
     url : 'UploadAction',//upload.php 
     chunk_size : '1mb', 
     method:'POST', 
     flash_swf_url : 'js/Moxie.swf', 
     silverlight_xap_url : 'js/Moxie.xap', 

     filters : { 
      max_file_size : '100gb', 
      mime_types: [ 
       {title : "Image files", extensions : "jpg,gif,png"}, 
       {title : "Zip files", extensions : "zip,txt,vmdk"} 
      ] 
     }, 
     init: { 
      PostInit: function() { 
       document.getElementById('filelist').innerHTML = ''; 
       document.getElementById('uploadfiles').onclick = function() { 
        uploader.start(); 
        return false; 
       }; 
      }, 
      FilesAdded: function(up, files) { 
       plupload.each(files, function(file) { 
        document.getElementById('filelist').innerHTML += '<div id="' + file.id + '">' + file.name + ' (' + plupload.formatSize(file.size) + ') <b></b></div>'; 
       }); 
      }, 
      UploadProgress: function(up, file) { 
       document.getElementById(file.id).getElementsByTagName('b')[0].innerHTML = '<span>' + file.percent + "%</span>"; 
      }, 
      Error: function(up, err) { 
       document.getElementById('console').appendChild(document.createTextNode("\nError #" + err.code + ": " + err.message)); 
      } 
     } 
    }); 
    uploader.init(); 
    </script> 
    </body> 
    </html> 
<!-- end snippet --> 

我的Java后端代码(Servlet的)是下: -

import java.io.BufferedOutputStream; 
import java.io.File; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.OutputStream; 
import javax.servlet.ServletException; 
import javax.servlet.ServletOutputStream; 
import javax.servlet.http.HttpServlet; 
import javax.servlet.http.HttpServletRequest; 
import javax.servlet.http.HttpServletResponse; 
import org.apache.commons.fileupload.FileItemIterator; 
import org.apache.commons.fileupload.FileItemStream; 
import org.apache.commons.fileupload.servlet.ServletFileUpload; 
import org.apache.commons.fileupload.util.Streams; 
public class UploadAction extends HttpServlet { 
    private static final long serialVersionUID = 3447685998419256747L; 
    private static final String RESP_SUCCESS = "{\"jsonrpc\" : \"2.0\", \"result\" : \"success\", \"id\" : \"id\"}"; 
    private static final String RESP_ERROR = "{\"jsonrpc\" : \"2.0\", \"error\" : {\"code\": 101, \"message\": \"Failed to open input stream.\"}, \"id\" : \"id\"}"; 
    public static final String JSON = "application/json"; 
    public static final int BUF_SIZE = 2 * 1024; 
    public static final String FileDir = "/home/asjha/uploads/"; 

    private int chunk; 
    private int chunks; 
    private String name; 
    private String user; 
    private String time; 
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 
     String responseString = RESP_SUCCESS; 
     boolean isMultipart = ServletFileUpload.isMultipartContent(req); 

     if(isMultipart){ 
      ServletFileUpload upload = new ServletFileUpload(); 
      try { 
       FileItemIterator iter = upload.getItemIterator(req); 
       while (iter.hasNext()) { 
        FileItemStream item = iter.next(); 
        InputStream input = item.openStream(); 
        // Handle a form field. 
        if(item.isFormField()){ 
         String fileName = item.getFieldName(); 
         String value = Streams.asString(input); 
         if("name".equals(fileName)){ 
          this.name = value; 
         }else if("chunks".equals(fileName)){ 
          this.chunks = Integer.parseInt(value); 
         }else if("chunk".equals(fileName)){ 
          this.chunk = Integer.parseInt(value); 
         }else if("user".equals(fileName)){ 
          this.user = value; 
         }else if("time".equals(fileName)){ 
          this.time = value; 
         } 
        } 

        // Handle a multi-part MIME encoded file. 
        else { 
         File dstFile = new File(FileDir); 
         if (!dstFile.exists()){ 
          dstFile.mkdirs(); 
         } 

         File dst = new File(dstFile.getPath()+ "/" + this.name); 

         saveUploadFile(input, dst); 
        } 
       } 
      } 
      catch (Exception e) { 
       responseString = RESP_ERROR; 
       e.printStackTrace(); 
      } 
     } 

     // Not a multi-part MIME request. 
     else { 
      responseString = RESP_ERROR; 
     } 

     if(this.chunk == this.chunks - 1){ 
      System.out.println("name"+this.name); 
     } 
     resp.setContentType(JSON); 
     byte[] responseBytes = responseString.getBytes(); 
     resp.setContentLength(responseBytes.length); 
     ServletOutputStream output = resp.getOutputStream(); 
     output.write(responseBytes); 
     output.flush(); 
    } 
    private void saveUploadFile(InputStream input, File dst) throws IOException { 
     OutputStream out = null; 
     try { 
      if (dst.exists()) { 
       out = new BufferedOutputStream(new FileOutputStream(dst, true), 
         BUF_SIZE); 
      } else { 
       out = new BufferedOutputStream(new FileOutputStream(dst), 
         BUF_SIZE); 
      } 
      byte[] buffer = new byte[BUF_SIZE]; 
      int len = 0; 
      while ((len = input.read(buffer)) > 0) { 
       out.write(buffer, 0, len); 
      } 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } finally { 
      if (null != input) { 
       try { 
        input.close(); 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } 
      } 
      if (null != out) { 
       try { 
        out.close(); 
       } catch (IOException e) { 
        e.printStackTrace(); 
       } 
      } 
     } 
    } 
} 

请参考plupload的细节,在GitHub上,你可以看到示例项目由jakobadam和岩石。

请让我知道是否需要多个文件上传。使用plupload,我们可以上传任意数量的任意大小的文件。此示例适用于超大尺寸的单个文件上传。 不要忘记包含plupload.full.min.js。希望这有助于*强调文本**

+0

如果我们没有像nginx一样的超时问题,也可以使用Apache commons。Plupload提供了许多使用flash,applet等上传的方法。 – 2015-04-08 19:16:13

0

如果您使用Java,请使用Arivus Nioserver gradle dependency - > compile'org.arivu:nioserver:1.0.3'。没有文件大小限制。

相关问题