开发者

Sending binary data to a servlet

I am trying send a file to a servlet.

function sendToServlet(){

var file = Components.classes["@mozilla.org/file/local;1"].  
           createInstance(Components.interfaces.nsILocalFile);  
file.initWithPath("C:\\Documents and Settings\\me\\Meus documentos\\Downloads\\music.mp3"); 

var boundary = "--------------" + (new Date).getTime();

var stream = Components.classes["@mozilla.org/network/file-input-stream;1"]  
                       .createInstance(Components.interfaces.nsIFileInputStream);  
stream.init(file, 0x04 | 0x08, 0644, 0x04); // file is an nsIFile instance     


// Send      
var req = Components.classes["@mozilla.org/xmlextras/xmlhttprequest;1"]  
                    .createInstance(Components.interfaces.nsIXMLHttpRequest);  
req.open('POST', 'http://localhost:8080/app/server'  , false); 
var contentType = "multipart/form-data; boundary=" + boundary;
    req.setRequestHeader("Content-Type", contentType);
req.send(stream);  

}

The source of javascript: https://developer.mozilla.org/En/XMLHttpRequest/Using_XMLHttpRequest#Sending_binary_data

But does not work.

Hi, this the serlevt code used:

protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub

         int size = 1024*20000;  
         long sizeFile = 0;
         File savedFile = null;      

         boolean isMultipart = ServletFileUpload.isMultipartContent(request);
         if (!isMultipart) {
         } else {
               FileItemFactory factory = new DiskFileItemFactory();
               ServletFileUpload upload = new ServletFileUpload(factory);
               upload.setFileSizeMax(new Long("-1"));
               List items = null;
               try {
                   items = uplo开发者_如何学运维ad.parseRequest(request);
               } catch (FileUploadException e) {
                   e.printStackTrace();
               }
               Iterator itr = items.iterator();
               while (itr.hasNext()) {
               FileItem item = (FileItem) itr.next();

                   try {

                       if (item.isFormField()) {
                            ;
                       }else{

                           String itemName = item.getName();
                           int sizeName = itemName.length();
                           int end  = itemName.indexOf('\n');
                           int start = itemName.lastIndexOf('\\');
                           itemName = itemName.substring(start + 1, sizeName-end-1);

                           savedFile = new File("C:\\Documents and Settings\\eric.silva\\Meus documentos\\"+itemName);
                           item.write(savedFile);  
                       }                       

                   } catch (Exception e) {
                       e.printStackTrace();
                   }
               }
           }
    }//metodo

But when i try to send a file the servlet dont create the file sent. Quando eu tento enviar via javascript a requisição é enviada. Mas o arquivo não é criado no lado do servidor. Acredito que o código apresentado no site da MDN esteja incompleto.

When I try to send via javascript the request is sent. But the file is not created on the server side. I believe the code shown on the site of the MDN is incomplete.


Note how the example code you are using is sending data with method PUT - valid multipart-formdata request needs to have some additional headers, not only the file itself. For example, the file you are sending should have a name (normally the name of the form field). You should use a FormData object instead, it will generate a valid request automatically. You should be able to create a File object directly. Something along these lines:

var file = File("C:\\Documents and Settings\\me\\Meus documentos\\Downloads\\music.mp3");
var data = new FormData();
data.append("file", file);
var req = Components.classes["@mozilla.org/xmlextras/xmlhttprequest;1"]  
                    .createInstance(Components.interfaces.nsIXMLHttpRequest);  
req.open('POST', 'http://localhost:8080/app/server', false);
request.send(data);

Note that creating File objects like this is only supported starting with Firefox 6.


The problem lies more likely in how you're trying to obtain the uploaded file with the servlet. Being a low level impelementation, the servlet doesn't have much of an abstraction for handling uploaded files (multi part requests). Luckily there are libraries who take care of that for you like commons.FileUpload:

http://commons.apache.org/fileupload/using.html

Just set up a servlet with fileUpload like it sais in the doc, then make a simple html page with a form that has a file upload input, and use that as a basic functional test to see that it works, then return to making your own client.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜