【问题标题】:struts how to set specific name to uploaded filestruts如何为上传的文件设置特定名称
【发布时间】:2014-04-29 04:26:58
【问题描述】:

我想为目标文件夹中上传的文件指定特定名称.. 这是我的操作文件代码.. 在这里我想给出 CPIC_1.jpg、CPIC_2.jpg、CPIC_3.jpg、CPIC_4.jpg 等名称但每次它分配名称时:CPIC_1.jpg ..所以我如何声明变量 ext 以便它在整个过程中是不同的..

CommercialFileBean b = (CommercialFileBean) form;
FormFile f = b.getF();
String s = request.getParameter("action");
HttpSession session = request.getSession(false);
String n = (String) session.getAttribute("str");
String email = session.getAttribute("uname").toString();
String status = (String) session.getAttribute("status");
String type = request.getParameter("type");
String pid;
long ext=0;
int id;
if (s.equalsIgnoreCase("finish")) {
    return mapping.findForward(next);
} else {   /// first else
    String a = getServlet().getServletContext().getRealPath("/");
    File file = new File(a + "uploaded/CPIC_"+ ++ext+".jpg");
    if (!file.exists()) {
        FileOutputStream out = new FileOutputStream(file);
        out.write(f.getFileData());
        out.close();
    }
    try {

        if (n.equalsIgnoreCase("rent")) {
            Session sess = UtilClass.createSession();
            Transaction tx = sess.beginTransaction();
            if (status.equalsIgnoreCase("new")) {
                String sql1 = "select MAX(id) from Rentcommercialrecord where loginid=:email";
                Query q1 = sess.createQuery(sql1);
                q1.setParameter("email", email);
                //  JOptionPane.showMessageDialog(null, "max id is :");
                List<Rentcommercialrecord> l = q1.list();
                Rentcommercialrecord rc = l.get(l.size()-1);
                id = rc.getId();
            } else {
                pid = (String) session.getAttribute("id");
                id = Integer.parseInt(pid);
            }
            JOptionPane.showMessageDialog(null, " latest id is :" + id);
            if (type.equalsIgnoreCase("frontpic")) {
                try {
                    String file1 = f.getFileName();
                    JOptionPane.showMessageDialog(null, "file name is : "+file1);
                    Rentcommercialrecord rc1 = (Rentcommercialrecord) sess.get(Rentcommercialrecord.class, id);
                    rc1.setImg1("CPIC_" +ext+".jpg");
                    sess.update(rc1);
                   // JOptionPane.showMessageDialog(null, "img1");

                } // img1 try ends
                catch (Exception e) {
                    JOptionPane.showMessageDialog(null, "Second error is : " + e.getMessage());
                }
            } // fontpic if ends
            else {
                try {

                    String file1 = f.getFileName();
                    JOptionPane.showMessageDialog(null, "file name is : "+file1);
                    Rentcommercialrecord rc1 = (Rentcommercialrecord) sess.get(Rentcommercialrecord.class, id);
                    rc1.setImg2("CPIC_" +ext+".jpg");
                    sess.update(rc1);
                   // JOptionPane.showMessageDialog(null, "img2");

                } // img2 try ends
                catch (Exception e) {
                    JOptionPane.showMessageDialog(null, "Second error is : " + e.getMessage());
                }
            }   // else img2 ends

            // l.size if ends
            tx.commit();
        }

【问题讨论】:

  • 变量的作用域属于action,所以你又开始指望下一次action调用了。

标签: java file-upload struts2 filenames


【解决方案1】:

将变量ext 设为static

static long ext = 0;

这将使变量对所有实例都通用。

注意:您需要在重新启动期间将此值存储在 db / 文件中的某个位置,并在应用程序启动期间获取它以使其保持一致,而不管您的应用程序是否重新启动

【讨论】:

  • 我在我的操作文件中使用了静态关键字作为 ext,但它给了我错误,比如 illgegal start of expression..
  • 我认为您是在方法级别声明它。 static 方法级别不允许使用变量。 static 变量应该在类级别声明
  • 正是所以我的问题是我必须在哪里声明这个变量 ext.. 我可以在 bean 中设置名称.. 在 bean 中我创建 getter setter 方法并在 set 方法中分配这个 ext var 名称?
【解决方案2】:

你可以让你的ext变量static

注意:您的静态变量的范围是针对当前类加载器的。即,如果它是一个 diff 类加载器被使用,这将改变。

其他选项是将ext 值存储在session 中,每次上传新图像文件时,从会话中获取该值并使用它。您还需要将新值放回会话中。这种方法适用于每个用户。即,如果您的应用程序有差异用户,对于差异用户,它将具有基于会话的差异值

【讨论】:

    【解决方案3】:

    您可以使用静态变量,但在应用程序重新启动时会不一致。

    我会改变方法并读取文件名,然后从它们的名称中提取数字,获取最高值,将其递增,然后写入一个新文件。

    使用Apache Commons 避免重复造轮子。

    启动示例:

    String path = getServlet().getServletContext().getRealPath("/") + "uploaded/";
    String partialName = "CPIC_";    
    int markerLength = partialName.length();
    int maxValue = 0;
    
    // Find all files, if any, with name starting with "CPIC_" in the desired folder
    List<File> files = FileUtils.listFiles(new File(path), 
                                           new PrefixFileFilter(partialName), 
                                           null);
    
    if (!files.isEmpty()){
        for (File file : files) {
            // Strip marker and extension
            int num = Integer.parseInt(
                         file.getName().substring(markerLength,
                                                  file.getName().indexOf("."))
                      );
            // compare the number, if greater, set as new max value
            if (num > maxValue) {
                maxValue = num;
            }
        }
    }
    
    String newFile = partialName + ++maxValue + ".jpg";
    System.out.println("Next file name would be : " + newFile);
    

    【讨论】:

    • 但我必须把这段代码放在我的意思是在写文件之后或之前因为我已经尝试过首先我正在写文件然后在那个动作页面中我写了这段代码然后再次写文件然后它给出如下错误:java.io.FileNotFoundException: CPIC_2.jpg (Access is denied)
    • 此代码将为您提供正确的文件名(最新的现有文件编号 + 1)。把它放在一个方法中,并返回文件对象。记得添加 Apache Commons .jar 库,并导入 FileUtils 和 PrefixFileFilter。
    • 字符串路径 = getServlet().getServletContext().getRealPath("/") + "upload/";文件 nf=fileMethod.method1(路径); fileUploadBean b=(fileUploadBean) 形式;表单文件 f=b.getF(); if(!nf.exists()) { FileOutputStream out=new FileOutputStream(nf); out.write(f.getFileData()); out.close();我已经使用了这段代码,但它又给了我类似的错误:java.io.FileNotFoundException: CPIC_1.jpg (Access is denied)
    • 我添加了 jar 文件,还导入了 FileUtils 和 PrefixFileFilter。
    猜你喜欢
    • 1970-01-01
    • 2018-09-13
    • 2012-06-22
    • 2018-12-22
    • 1970-01-01
    • 1970-01-01
    • 2020-07-31
    • 2015-10-15
    • 2017-04-24
    相关资源
    最近更新 更多