как загрузить файл - PullRequest
       10

как загрузить файл

0 голосов
/ 09 сентября 2011

я пытаюсь загрузить файл с клиента на сервер

на стороне клиента, у меня есть файл ввода

на стороне сервера, у меня есть

 private void uploadFile(final FileTransfer fileTransfer) {

    String destinationFile = "/home/nat/test.xls";
    InputStream fis = null;
    FileOutputStream out = null;
    byte buf[] = new byte[1024];
    int len;
    try {
        fis = fileTransfer.getInputStream();
        out = new FileOutputStream(new File(destinationFile));

        while ((len = fis.read(buf)) > 0) {
            out.write(buf, 0, len);
        }

    } 
}

aфайл создается на сервере, но при отладке он пуст, я вижу, что fis не равен нулю

есть идеи?

1 Ответ

0 голосов
/ 15 декабря 2011

Вот мой фрагмент кода:

    try {    
        File fileData = new File(fileTransfer.getFilename());         

        // Write the content (data) in the file
        // Apache Commons IO: (FileUtils)
        FileOutputStream fos = FileUtils.openOutputStream(fileData);
        // Spring Utils: FileCopyUtils 
        FileCopyUtils.copy(fileTransfer.getInputStream(), fos);

        // Alternative with Apache Commons IO
        // FileUtils.copyInputStreamToFile(fileTransfer.getInputStream(), fileData);


    // Send the file to a back-end service
    myService.persistFile( fileData );

    } catch (IOException ioex) {
        log.error("Error with io")
    }
    return fileTransfer.getFilename(); // this is for my javascript callback fn

Apache Commons IO - хорошая библиотека для таких манипуляций (я также использую Spring Utils).Если у вас нет контекста Spring, используйте закомментированную альтернативу с Apache (проверьте синтаксис, он не проверен).

...