Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

提供相关JAVA上传附件代码 #22

Open
kuhnpeng opened this issue Mar 14, 2020 · 0 comments
Open

提供相关JAVA上传附件代码 #22

kuhnpeng opened this issue Mar 14, 2020 · 0 comments

Comments

@kuhnpeng
Copy link

kuhnpeng commented Mar 14, 2020

可上传图片,视频及其他文件,支付多个上传。
FileController.java

@PostMapping("/uploadFile")
    public R uploadFile(HttpServletRequest request){
        UploadFileResponse uploadFileResponse = null;
        // 将当前上下文初始化给 CommonsMutipartResolver (多部分解析器)
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
                request.getSession().getServletContext());
        // 检查form中是否有enctype="multipart/form-data"
        if (multipartResolver.isMultipart(request)) {
            // 将request变成多部分request
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;
            // 获取multiRequest 中所有的文件名
            Iterator iter = multiRequest.getFileNames();

            while (iter.hasNext()) {
                // 一次遍历所有文件
                MultipartFile file = multiRequest.getFile(iter.next()
                        .toString());
                //传递参数值
//                String str = multiRequest.getParameter("str");
//                System.out.println("str:" + str);
                if (Objects.nonNull(file)) {
                    uploadFileResponse = fileService.storeSingleFile(file);
                }

            }

        }

        return R.OK().setData(uploadFileResponse);
    }

FileService.java

 * 存储文件到系统
     *
     * @param file 文件
     * @return 文件名
     */
    public UploadFileResponse storeSingleFile(MultipartFile file) {
        String extension = FilenameUtils.getExtension(file.getOriginalFilename());
        String fileName = FilenameUtils.getName(file.getOriginalFilename());

        if(fileName.contains("..")) {
            throw new FileException("Sorry! Filename contains invalid path sequence " + fileName);
        }
        try {
            Path targetLocation = this.fileStorageLocation.resolve(fileName);
            Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING);
            return new UploadFileResponse(file.getName(),fileName,extension,file.getSize());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant