簡體   English   中英

如何指定要在Web Service中上載的文件類型

[英]How to specify type of file to be uploaded in Web Service

我正在做Web服務,昨天才開始。 我的知識很淺,因為我以前從未學過。

我有如下代碼

@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;
}

基本上,它將文件從目錄移動到另一個目錄。 我現在要指定要移動的文件的類型,而我只想移動圖像類型的文件(jpg,jpeg,png等)。 如何在代碼中指定呢?

您可以檢查文件的mime類型,以檢查上傳的文件是否符合您的興趣。
有某些庫可用,例如JMimeMagicApache Tika
否則,您也可以看到答案以供參考。

我將以字符串形式獲取文件名,並使用“。”將其拆分為一個數組。 作為分隔符,然后獲取數組的最后一個索引,即文件擴展名。 例如:

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

那么您得到的擴展名是.jpg。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM