Download Vaadin:下载的文件具有完整的路径作为文件名

Download Vaadin:下载的文件具有完整的路径作为文件名,download,filenames,vaadin,Download,Filenames,Vaadin,我在我的Vaadin应用程序上实现了一个下载操作,但由于某些原因,下载的文件将原始文件的完整路径作为文件名 有什么想法吗 你可以看到代码 编辑: 以下是代码的重要部分: package com.bluecubs.xinco.core.server.vaadin; import com.bluecubs.xinco.core.server.XincoConfigSingletonServer; import com.vaadin.Application; import com.vaadin.te

我在我的Vaadin应用程序上实现了一个下载操作,但由于某些原因,下载的文件将原始文件的完整路径作为文件名

有什么想法吗

你可以看到代码

编辑:

以下是代码的重要部分:

package com.bluecubs.xinco.core.server.vaadin;

import com.bluecubs.xinco.core.server.XincoConfigSingletonServer;
import com.vaadin.Application;
import com.vaadin.terminal.DownloadStream;
import com.vaadin.terminal.FileResource;
import java.io.*;
import java.net.URLEncoder;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.zip.CRC32;
import java.util.zip.CheckedInputStream;

/**
 *
 * @author Javier A. Ortiz Bultrón<javier.ortiz.78@gmail.com>
 */
public class FileDownloadResource extends FileResource {

    private final String fileName;
    private File download;
    private File newFile;

    public FileDownloadResource(File sourceFile, String fileName,
            Application application) {
        super(sourceFile, application);
        this.fileName = fileName;
    }

    protected void cleanup() {
        if (newFile != null && newFile.exists()) {
            newFile.delete();
        }
        if (download != null && download.exists() && download.listFiles().length == 0) {
            download.delete();
        }
    }

    @Override
    public DownloadStream getStream() {
        try {
            //Copy file to directory for downloading
            InputStream in = new CheckedInputStream(new FileInputStream(getSourceFile()),
                    new CRC32());
            download = new File(XincoConfigSingletonServer.getInstance().FileRepositoryPath
                    + System.getProperty("file.separator") + UUID.randomUUID().toString());
            newFile = new File(download.getAbsolutePath() + System.getProperty("file.separator") + fileName);
            download.mkdirs();
            OutputStream out = new FileOutputStream(newFile);
            newFile.deleteOnExit();
            download.deleteOnExit();
            byte[] buf = new byte[1024];
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            in.close();
            out.close();
            final DownloadStream ds = new DownloadStream(
                    new FileInputStream(newFile), getMIMEType(), fileName);
            ds.setParameter("Content-Disposition", "attachment; filename="
                    + URLEncoder.encode(fileName, "utf-8"));
            ds.setCacheTime(getCacheTime());
            return ds;
        } catch (final FileNotFoundException ex) {
            Logger.getLogger(FileDownloadResource.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        } catch (IOException ex) {
            Logger.getLogger(FileDownloadResource.class.getName()).log(Level.SEVERE, null, ex);
            return null;
        }
    }
}
package com.bluecubs.xinco.core.server.vaadin;
导入com.bluecubs.xinco.core.server.XincoConfigSingletonServer;
导入com.vaadin.Application;
导入com.vaadin.terminal.DownloadStream;
导入com.vaadin.terminal.FileResource;
导入java.io.*;
导入java.net.urlcoder;
导入java.util.UUID;
导入java.util.logging.Level;
导入java.util.logging.Logger;
导入java.util.zip.CRC32;
导入java.util.zip.CheckedInputStream;
/**
*
*@作者Javier A.Ortiz Bultron
*/
公共类FileDownloadResource扩展了FileResource{
私有最终字符串文件名;
私人文件下载;
私有文件newFile;
公共文件下载资源(文件源文件、字符串文件名、,
应用程序(应用程序){
超级(源文件、应用程序);
this.fileName=文件名;
}
受保护的空清除(){
if(newFile!=null&&newFile.exists()){
newFile.delete();
}
if(download!=null&&download.exists()&&download.listFiles().length==0){
下载.删除();
}
}
@凌驾
公共下载流getStream(){
试一试{
//将文件复制到目录以便下载
InputStream in=new CheckedInputStream(新文件InputStream(getSourceFile()),
新的CRC32());
下载=新文件(XincoConfigSingletonServer.getInstance().FileRepositoryPath
+System.getProperty(“file.separator”)+UUID.randomUUID().toString();
newFile=新文件(download.getAbsolutePath()+System.getProperty(“File.separator”)+文件名);
下载.mkdirs();
OutputStream out=新文件OutputStream(新文件);
newFile.deleteOnExit();
下载.deleteOnExit();
字节[]buf=新字节[1024];
内伦;
而((len=in.read(buf))>0){
out.write(buf,0,len);
}
in.close();
out.close();
最终下载流ds=新下载流(
新文件输入流(newFile),getMIMEType(),文件名);
setParameter(“内容处置”、“附件;文件名=”
+encode(文件名,“utf-8”);
setCacheTime(getCacheTime());
返回ds;
}捕获(最终文件NotFoundException ex){
Logger.getLogger(FileDownloadResource.class.getName()).log(Level.SEVERE,null,ex);
返回null;
}捕获(IOEX异常){
Logger.getLogger(FileDownloadResource.class.getName()).log(Level.SEVERE,null,ex);
返回null;
}
}
}

我已经调试并验证了文件名只包含文件名,而不是整个路径。

以下是我的代码,工作正常(将blob作为文件从数据库下载),但它使用Servlet和OutputStream,而不是DownloadStream:

public class TextFileServlet extends HttpServlet
{
    public static final String PARAM_BLOB_ID = "id";

    private final Logger logger = LoggerFactory.getLogger(TextFileServlet.class);

    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException
    {
        Principal userPrincipal = req.getUserPrincipal();
        PersistenceManager pm = PMFHolder.get().getPersistenceManager();
        Long id = Long.parseLong(req.getParameter(PARAM_BLOB_ID));
        MyFile myfile = pm.getObjectById(MyFile.class, id);

        if (!userPrincipal.getName().equals(myfile.getUserName()))
        {
            logger.info("TextFileServlet.doGet - current user: " + userPrincipal + " file owner: " + myfile.getUserName());
            return;
        }

        res.setContentType("application/octet-stream");
        res.setHeader("Content-Disposition", "attachment;filename=\"" + myfile.getName() + "\"");
        res.getOutputStream().write(myfile.getFile().getBytes());
    }
}

我希望它能帮助你。

答案实际上是houman001的答案和这篇文章的混合:

我不再采用上述方法,而是采用更简单的工作方法:

         StreamSource ss = new StreamSource() {

            byte[] bytes = //Get the file bytes here
            InputStream is = new ByteArrayInputStream(bytes);

            @Override
            public InputStream getStream() {
                return is;
            }
        };
        StreamResource sr = new StreamResource(ss, <file name>, <Application Instance>);
        getMainWindow().open(sr, "_blank");
StreamSource ss=new StreamSource(){
byte[]bytes=//在此处获取文件字节
InputStream is=新的ByteArrayInputStream(字节);
@凌驾
公共输入流getStream(){
回报是;
}
};
StreamResource sr=新的StreamResource(ss,);
getMainWindow()。打开(sr,“_blank”);

如果能在这里直接查看一些代码就好了……在这里添加了代码,只是为了避免重复。这会的,但我当前的代码(当前发布的)就是这样做的。我正在迁移到Vaadin。您的回答让我想起我的web服务仍然可用,这会引导我找到答案。完成后,我无法找到答案。当我这样做时,我不得不等待一段时间(弹出消息)@javydreamercsw非常感谢。
StreamResource myResource = createResource(attachmentName);
System.out.println(myResource.getFilename());
if(attachmentName.contains("/"))
   attachmentName = attachmentName.substring(attachmentName.lastIndexOf("/"));
if(attachmentName.contains("\\"))
   attachmentName = attachmentName.substring(attachmentName.lastIndexOf("\\"));
myResource.setFilename(attachmentName);
FileDownloader fileDownloader = new FileDownloader(myResource);
fileDownloader.extend(downloadButton);