Java 从上传的文件中获取文件扩展名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23885042/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 08:51:07  来源:igfitidea点击:

Get file extension from uploaded file

javaplayframeworkapache-commons-fileupload

提问by svjn

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"

“/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:

HTML代码:

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

Get file object from Play framework:

从 Play 框架获取文件对象:

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

Any help to extract file extension is highly appreciated.

非常感谢提取文件扩展名的任何帮助。

Thanks,

谢谢,

采纳答案by svjn

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

我已经找到了解决方案。实际上这是Play框架。我使用以下代码获取了文件。

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

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

我尝试使用此File对象(用于存储在tmp位置)获取文件的名称。但是我没有注意到FilePart对象包含所有上传的文件详细信息。然后我想通了。

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

fileInput.getFilename()给我带扩展名的上传文件名。它解决了我的问题。

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

感谢Cataclysm帮助我。当然,他给出的答案是其他框架(如 Struts/Spring 或核心 servlet)的最佳答案。

回答by Cataclysm

I used Jquery fileuploadin client side.

我在客户端使用了Jquery fileupload

And at my JS file ,

在我的 JS 文件中,

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

处理您对图片上传的特定请求(我使用的是 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();
}

回答by Aditya Agarwal

This worked for me

这对我有用

Part filePart = request.getPart("input-file"); 
String type=filePart.getContentType();
type="."+type.substring(type.lastIndexOf("/")+1);