简体   繁体   中英

struts how to set specific name to uploaded file

i want to give specific name to the uploaded file in my destination folder.. this is my action file code.. here i want to give name like CPIC_1.jpg,CPIC_2.jpg,CPIC_3.jpg,CPIC_4.jpg etc but every time it is assigning name : CPIC_1.jpg.. so how i declare variable ext so that through out it will be distinct..

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();
        }

Make your variable ext as static .

static long ext = 0;

This will make the variable common to all instances.

Note : You need to store this value somewhere in db / file during restart and get it during application startup to make it consistent irrespective of restart of your application

You can make your ext variable static

Note: The scope of your static variable is for the current class Loader. ie, if it is a diff class loader is used , this will change.

other option is store the ext value in session and every time you upload a new image file, get this value from session and use it. And you need to put the new value back into session as well. This approach will work for per user. ie if your application is having diff users, for diff users it will have diff value based on session

You can use a static variable, but it won't be consistent through application restarts.

I would change approach and would read filenames, then extracting the numbers from their names, getting the highest, incrementing it and then writing a new file.

Use Apache Commons to avoid reinventing the wheel.

Kickoff example:

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM