java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > Java多种文件上传方式

Java中的多种文件上传方式总结

作者:enjoy嚣士

这篇文章主要介绍了Java中的多种文件上传方式总结,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教

请求类型

在这里插入图片描述

单文件上传

在这里插入图片描述

    //上传单个文件
    @ResponseBody
    @RequestMapping(value = "uploadfile", produces = "multipart/form-data;charset=UTF-8")
    public String uploadfiles(HttpServletRequest request){
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        if (multipartResolver.isMultipart(request)) {
            DefaultMultipartHttpServletRequest multipartRequest = (DefaultMultipartHttpServletRequest) request;
            MultipartFile multipartFile = multipartRequest.getFile("file");
            if (multipartFile == null) {
                System.out.println("multipartFile == null");
            }
            String filename = multipartRequest.getFile("file").getOriginalFilename();
            String tmpFile = request.getSession().getServletContext().getRealPath("/") + UUID.randomUUID().toString().replace("-", "") + ".apk";
            File targetFile = new File(tmpFile);
            AppEntity appEntity = new AppEntity();
            if (null != multipartFile) {
                //保存文件
                try {
                    multipartFile.transferTo(targetFile);
                } catch (IllegalStateException e) {
                    logger.error("multipartFile.transferTo, IllegalStateException", e);
                } catch (IOException e) {
                    logger.error("multipartFile.transferTo, IOException", e);
                }
            }
        }
        return "";
    }

多文件上传

多文件单字段上传

在这里插入图片描述

    @ResponseBody
    @RequestMapping(value = "uploadfiles", produces = "multipart/form-data;charset=UTF-8")
    public String uploadfile(MultipartHttpServletRequest request){
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        if (multipartResolver.isMultipart(request)) {
            //上传多个文件,一个字段中包含多个文件
            String projectPath = request.getSession().getServletContext().getRealPath("/");
            MultiValueMap<String, MultipartFile> multiFileMap = request.getMultiFileMap();
            List<MultipartFile> fileSet = new LinkedList<>();
            for(Map.Entry<String, List<MultipartFile>> temp : multiFileMap.entrySet()){
                fileSet = temp.getValue();
            }
            for(MultipartFile temp : fileSet){
                File file2 = new File(projectPath+temp.getOriginalFilename());
                try {
                    temp.transferTo(file2);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return "";
    }

多文件多字段上传

在这里插入图片描述

    @ResponseBody
    @RequestMapping(value = "uploadfiles", produces = "multipart/form-data;charset=UTF-8")
    public String uploadfile(MultipartHttpServletRequest request){
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        if (multipartResolver.isMultipart(request)) {
            //上传多个文件,每个字段一个文件
            Iterator<String> fileNames = request.getFileNames();
            while (fileNames.hasNext()){
                // 取得上传文件
                String uploadName = fileNames.next();
                MultipartFile file = request.getFile(uploadName);
                if (file != null) {
                    String projectPath = request.getSession().getServletContext().getRealPath("/");
                    String originalFilename = file.getOriginalFilename();
                    String tmpFile = projectPath + System.currentTimeMillis() + "_" + originalFilename;
                    File targetFile = new File(tmpFile);
                    try {
                        file.transferTo(targetFile);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return "";
    }

如果上面方法不行,看下面

@PostMapping(value = "test", produces = "multipart/form-data;charset=UTF-8")
public void UploadFiles(HttpServletRequest request) throws IOException {
    //如果请求中包含文件
    if(ServletFileUpload.isMultipartContent(request)){
        // 创建一个通用的多部分解析器
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        List<MultipartFile> files = multipartRequest.getFiles("file");
        File targetFile;
        for (MultipartFile file : files){
            //保存文件到本地
            String projectPath = request.getSession().getServletContext().getRealPath("/");
            projectPath = projectPath + System.currentTimeMillis() + "_" + new Random().nextInt(100);
            File dir = new File(projectPath);
            if (!dir.exists()){
                dir.mkdir();
            }
            String originalFilename = file.getOriginalFilename();
            String tmpFile = projectPath + File.separator + originalFilename;
            targetFile = new File(tmpFile);
            file.transferTo(targetFile);
            //将文件保存到本地并记录信息
            //...
        }
    }
}

还有一种方法,函数入参直接接受文件

例如:

//单文件
public String UploadFiles(@RequestParam("file") MultipartFile file){
}
//多文件
public String UploadFiles(@RequestParam("file") List<MultipartFile> files){
}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。

您可能感兴趣的文章:
阅读全文