0

I'm doing Web Service and just started yesterday. My knowledge is very shallow because I never learn this before.

I have the code as below

@WebMethod(operationName = "uploadImage")
public String uploadImage(@WebParam(name = "imagePath") String imagePath) {
    //TODO write your implementation code here:

    try{

       File afile =new File(imagePath);

       if(afile.renameTo(new File("D:\\" + afile.getName()))){
        return "Success";
       }else{
           return "Failed";
       }

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

    return null;
}

It basically move a file from a directory to another. What I want now is to specify the type of file(s) to be move and I just wanted to move image kind of file (jpg,jpeg,png, etc). How do I specify in my code for it?

user273371
  • 43
  • 1
  • 2
  • 7

2 Answers2

0

You can check the file mime type, to check whether file uploaded is of your interest or not.
There are certain library available e.g. JMimeMagic or Apache Tika.
else you can also see this answer for reference.

Community
  • 1
  • 1
Aman Gupta
  • 5,548
  • 10
  • 52
  • 88
0

I would get the file name as a String, split it into an array with "." as the delimiter, and then get the last index of the array, which would be the file extension. For example:

public class main {
    public static void main(String[] args) {
        String filename = "image.jpg";
        String filenameArray[] = filename.split("\\.");
        String extension = filenameArray[filenameArray.length-1];
        System.out.println(extension);
    }
}

then you get the extension is .jpg.

Harshit Rathi
  • 1,862
  • 2
  • 18
  • 25
  • @user273371 FYI I must tell you that check by file extension could be dangerous and may lead you toward code break. indeed above solution is quick one, but if you are more conscious, then you may have to look for alternate approach. – Aman Gupta Nov 25 '13 at 13:33