Get file extension from uploaded file

13,951

Solution 1

I have found the solution for this. Actually this is of Play framework. I got the file using following code.

MultipartFormData body = request().body().asMultipartFormData();
FilePart fileInput = body.getFile("fileInput");
File file = fileInput.getFile();

I tried to get the name of file using this File object (which is used to store in a tmp location). But I missed to notice that FilePart object contains all file details that was uploaded. Then I figured it out.

fileInput.getFilename() gives me the uploaded file name with extension. It solves my problem.

Thanks for Cataclysm for helping me out. Surely the one he gave is the best answer for other framework like Struts/Spring or core servlets.

Solution 2

I used Jquery fileupload in client side.

And at my JS file ,

function doUploadPhoto(seq) {
$('#fileupload').fileupload({
    url : 'news/upload.html?s=' + seq,
    sequentialUploads : true,
    disableImageResize : false,
    imageMaxWidth : 1024,
    imageMaxHeight : 1024,
    previewCrop : true,
    dropZone : $("#dropZone"),
    acceptFileTypes : /(\.|\/)(gif|jpe?g|png)$/i,
    progress : function(e, data) {
        if (data.context) {
            var progress = data.loaded / data.total * 100;
            progress = Math.floor(progress);
            $('.progress').attr('aria-valuenow', progress);
            $('.progress').css('display', 'block');
            $('.bar').css('width', progress + '%');
        }
    },
    progressall : function(e, data) {
        var progress = data.loaded / data.total * 100;
        progress = Math.floor(progress);
        $('.progressall').attr('aria-valuenow', progress);
        $('.progressall').css('display', 'block');
        $('.allbar').css('width', progress + '%');
        if (progress > 20) {
            $('.allbar').text(progress + '% Completed');
        }
    },
    stop: function (e) {
        return;
    }
});
}

Handle your specific request for image upload (I used Spring).

@RequestMapping(value = "/news/upload.html", method = RequestMethod.POST)
public final void uploadNewsPhoto(final HttpServletRequest request, final HttpServletResponse response)
        throws Exception {
    doUploadNewsPhoto(request, getSessionFileItems(request));
}

for upload image

public final synchronized String doUploadNewsPhoto(final HttpServletRequest request,
        final List<FileItem> sessionFiles) throws UploadActionException {

    try {
        List<Map<String, Object>> ret = new ArrayList<Map<String, Object>>();
        for (FileItem item : sessionFiles) {
            if (!item.isFormField()) {
                try {
                    // get news sequence for save it's images
                    Long seq = Long.parseLong(request.getParameter("s"));
                    Map<String, Object> res = newsPhotoBiz.saveToFile(seq, item, SecuritySession.getLoginUserSeq());

                    res.put("name", item.getName());
                    res.put("size", item.getSize());
                    ret.add(res);
                }
                catch (Exception e) {
                    log.error("Error, can't upload news photo file, name:" + item.getName(), e);
                }
            }
        }

        // Remove files from session because we have a copy of them
        removeSessionFileItems(request);

        Map<String, Object> json = new HashMap<String, Object>();
        json.put("files", ret);
        JSONObject obj = (JSONObject) JSONSerializer.toJSON(json);
        // return to client side about uploaded images info
        return obj.toString();
    }
    catch (Exception e) {
        log.error("Error, when upload news photo file", e);
        throw new UploadActionException(e);
    }
}

for save image

public final Map<String, Object> saveToFile(final Long newsSeq, final FileItem item, final Long loginUserSeq)
        throws BusinessException {
    String staticDir = System.getProperty("staticDir");

    Date today = new Date();
    SimpleDateFormat fmtYMD = new SimpleDateFormat("/yyyyMMdd");
    SimpleDateFormat fmtHMS = new SimpleDateFormat("HHmmssS");

    String saveDir = "data/news" + fmtYMD.format(today);
    String format = ".jpg";
    try {
        format = item.getName().substring(item.getName().lastIndexOf("."), item.getName().length());
    }
    catch (Exception e) {
      format = ".jpg";
    }

    try {
        String fileName = newsSeq + "_" + fmtHMS.format(today) + format;

        NewsPhotoBean bean = new NewsPhotoBean();
        bean.setNewsSeq(newsSeq);
        bean.setFile(saveDir + "/" + fileName);
           // save image infos in database and return it's sequence
        Long photoSeq = newsPhotoService.add(bean, loginUserSeq);

        // Save image in specify location
        String filePath = staticDir + "/" + saveDir;
        FileSupport.saveFile(filePath, fileName, item);

        Map<String, Object> ret = new HashMap<String, Object>();
        ret.put("seq", newsSeq);
        ret.put("photoSeq", photoSeq);
        ret.put("path", saveDir + "/" + fileName);
        ret.put("ext", format.substring(1));

       //client side may need uploaded images info
        return ret;
    }
    catch (Exception e) {
        throw new BusinessException("Error occur when save file. newsSeq : " + newsSeq, e);
    }
}

for write image

// Save Image by FileItem that gets from Image Upload
public static String saveFile(final String filePath, final String fileName, final FileItem item) throws Exception {
    File file = new File(filePath);
    file.setExecutable(true, false);
    file.setWritable(true, false);

    if (!file.exists()) {
        file.mkdirs();
    }

    File imageFile = new File(file, fileName);
    item.write(imageFile);
    item.setFieldName(filePath + fileName);

    return item.toString();
}

Solution 3

This worked for me

Part filePart = request.getPart("input-file"); 
String type=filePart.getContentType();
type="."+type.substring(type.lastIndexOf("/")+1);
Share:
13,951
svjn
Author by

svjn

Updated on June 11, 2022

Comments

  • svjn
    svjn almost 2 years

    Here my requirement is to upload the file and to store it in the disk. I have no problem in storing it in disk, but getting the extension of the file. The problem is when I click on upload and processing the file to store in disk, it is saved as a temp file with following name

    "/tmp/multipartBody6238081076014199817asTemporaryFile"

    here the file doesn't have an extension. So any of the following libraries doesn't help me get the extension of the file.

    FileNameUtils.getExtension()
    
    or
    
    Files.getFileExtension(path)
    

    I've even tried to get it through it's attributes, but it doesn't have an option to get the file extension.

    Path path = Paths.get("/**/**/filepath");
    BasicFileAttributes attr = Files.readAttributes(path, BasicFileAttributes.class);
    

    HTML code:

    <input type="file" name="fileInput" class="filestyle"  data-classIcon="icon-plus" data-classButton="btn btn-primary" >
    

    Get file object from Play framework:

    MultipartFormData body = request().body().asMultipartFormData();
    FilePart fileInput = body.getFile("fileInput");
    File file = fileInput.getFile();
    

    Any help to extract file extension is highly appreciated.

    Thanks,