【问题标题】:primeng p-fileUpload does not send the multipart file in weblogic 12cprimeng p-fileUpload 不会在 weblogic 12c 中发送多部分文件
【发布时间】:2018-03-21 02:35:28
【问题描述】:

我有一个带有控制器的 Spring Boot 应用程序,可以使用 p-fileUpload 从primeng 上传文件。当我在 STS 中将 Spring Boot 服务作为 Sprint Boot App 运行时,一切正常,但是当我将该服务部署到 weblogic 12c R2 (12.2.1.1) 时,控制器方法得到一个空列表。

代码如下。我需要做什么才能让 weblogic 正常工作?

        // 3.1.2 Multiple file upload
    // @PostMapping("/api/upload/multi")
//  @Consumes(MediaType.MULTIPART_FORM_DATA_VALUE)
    @ResponseBody
    @RequestMapping(value = { "/upload/multi/{fein}" }, method = { RequestMethod.POST })
    public ResponseEntity<?> uploadFileMulti(
            @PathVariable Long fein,
            // @RequestParam("extraField") String extraField,
            @RequestPart("uploadFiles") List<MultipartFile> myFiles) {

        log.info("Multiple file upload!");

        // Get file name
        // String uploadedFileName = Arrays.stream(uploadFiles).map(x ->
        // x.getOriginalFilename())
        // .filter(x -> !StringUtils.isEmpty(x)).collect(Collectors.joining(" ,
        // "));
        //
        // if (StringUtils.isEmpty(uploadedFileName)) {
        // return new ResponseEntity("please select a file!", HttpStatus.OK);
        // }

        // Check for empty files.
        for (MultipartFile myFile : myFiles) {
            log.info("Attempting to upload of files=" + myFile.getOriginalFilename());
            if (myFile.isEmpty()) {
                log.error("No file specified!");
                return new ResponseEntity<>("No file specified!", HttpStatus.BAD_REQUEST);
            }
        }

        try {

//          saveUploadedFiles( fein, Arrays.asList(myFiles));
            saveUploadedFiles( fein, myFiles);

        } catch (IOException e) {
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        }

        return new ResponseEntity<>("Successfully uploaded - file(s).", HttpStatus.OK);
    }

    <div class="container">
    <div class="row">
        <div class="col-md-12">
            <form [formGroup]="attachmentForm" (ngSubmit)="onSubmit()">
                <div class="row">
                    <div class="col-md-12">
                        <p-panel header="Instructions">
                            <ul class="no-list-style">
                                <li><label>Step 1: Click Browse to find the document(s) you want to upload</label></li>
                                <li><label>Step 2: Click Upload</label></li>
                                <li><label>Step 3: Click Save</label></li>
                            </ul>
                        </p-panel>
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-12">
                        <div class="form-group">
                            <p-fileUpload name="uploadFiles" url={{uploadUrlString}} accept={{acceptString}} maxFileSize="50000000" (onUpload)="onUpload($event)"></p-fileUpload>
                            <!-- <label>File Name</label>
                            <input type="text" class="form-control" value={{selectedAttachment.filName}} formControlName="filename" /> -->
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-12">
                        <div class="form-group">
                            <label>File Name</label>
                            <textarea class="form-control" value={{selectedAttachment.filName}} formControlName="filename"></textarea>
                        </div>
                    </div>
                </div>
                <div class="row">
                    <div class="col-md-12">
                        <div class="form-group">
                            <label>Comments</label>
                            <textarea class="form-control" value={{selectedAttachment.comments}} formControlName="comments"></textarea>
                        </div>
                    </div>
                </div>

                <div class="row">
                    <button type="submit" class="btn btn-primary btn-sm pull-left" style="margin-left:15px; margin-right:15px; margin-top:5px; margin-bottom:5px">Save Attachment</button>
                    <button type="button" class="btn btn-primary btn-sm pull-left" style="margin-left:15px; margin-right:15px; margin-top:5px; margin-bottom:5px"
                        (click)="onCancel()">Cancel</button>
                </div>
            </form>
        </div>
    </div>
</div>

【问题讨论】:

    标签: spring-boot weblogic12c primeng


    【解决方案1】:

    所以经过大量研究,结果证明这是 weblogic 12c 的解决方案。希望对大家有所帮助。

        package com.demo.configuration;
    
    import javax.persistence.EntityManagerFactory;
    import javax.sql.DataSource;
    
    import org.springframework.beans.factory.annotation.Qualifier;
    import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
    import org.springframework.boot.context.properties.ConfigurationProperties;
    import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
    import org.springframework.boot.web.servlet.FilterRegistrationBean;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.context.annotation.Primary;
    import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
    import org.springframework.orm.jpa.JpaTransactionManager;
    import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
    import org.springframework.orm.jpa.vendor.HibernateJpaSessionFactoryBean;
    import org.springframework.transaction.PlatformTransactionManager;
    import org.springframework.transaction.annotation.EnableTransactionManagement;
    import org.springframework.web.cors.CorsConfiguration;
    import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
    import org.springframework.web.filter.CorsFilter;
    import org.springframework.web.multipart.MultipartResolver;
    import org.springframework.web.multipart.commons.CommonsMultipartResolver;
    import org.springframework.web.servlet.config.annotation.CorsRegistry;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
    
    import com.demo.environment.DemoEnvironment;
    
    
    @Configuration
    @EnableTransactionManagement
    @EnableJpaRepositories(
            entityManagerFactoryRef = "entityManagerFactory", 
            basePackages = { "com.demo.dao.oracle" })
    public class OracleConfiguration {
    
        DemoEnvironment env = new DemoEnvironment();
    
        @Primary
        @Bean(name = "dataSource")
        @ConfigurationProperties(prefix="spring.oracle.datasource")
        public DataSource dataSource() {
            return DataSourceBuilder.create().build();
        }
    
    
        @Primary
        @Bean(name = "entityManagerFactory")
        public LocalContainerEntityManagerFactoryBean entityManagerFactory(
                EntityManagerFactoryBuilder builder,
                @Qualifier("dataSource") DataSource dataSource) {
            return builder
                    .dataSource(dataSource)
                    .packages("com.demo.entity")
                    .persistenceUnit("DEMO")
                    .build();
        }
    
        @Primary
        @Bean(name = "transactionManager")
        public PlatformTransactionManager transactionManager(
                @Qualifier("entityManagerFactory") EntityManagerFactory entityManagerFactory) {
            return new JpaTransactionManager(entityManagerFactory);
        }
    
        @Primary
        @Bean(name = "sessionFactory")
        public HibernateJpaSessionFactoryBean sessionFactory() {
            return new HibernateJpaSessionFactoryBean();
        }
    
        @Bean
        public WebMvcConfigurer corsConfigurer() {
            return new WebMvcConfigurerAdapter() {
                @Override
                public void addCorsMappings(CorsRegistry registry) {
                    registry.addMapping("/**");
                }
            };
        }
    
        @Bean
        public FilterRegistrationBean corsFilter() {
            UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
            CorsConfiguration config = new CorsConfiguration();
            config.setAllowCredentials(true);
            config.addAllowedOrigin("http://localhost:7001");
            String allowedOrigin = this.env.getAllowedOrigin();
            config.addAllowedOrigin(allowedOrigin);
            config.addAllowedHeader("*");
            config.addAllowedMethod("*");
            source.registerCorsConfiguration("/**", config);
            FilterRegistrationBean bean = new FilterRegistrationBean(new CorsFilter(source));
            bean.setOrder(0);
            return bean;
        }   
    
        @Bean
        public MultipartResolver multipartResolver() {
            return new CommonsMultipartResolver();
        }
    
    }
    
    pom.xml:
    
    <dependency>
        <groupId>commons-fileupload</groupId>
        <artifactId>commons-fileupload</artifactId>
        <version>1.3.3</version>
    </dependency>
    
    <!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
    <dependency>
        <groupId>commons-io</groupId>
        <artifactId>commons-io</artifactId>
        <version>2.6</version>
    </dependency>
    
    application.properties:
    
    spring.http.multipart.enabled=false
    
    
    Controller:
    
    /**
     * 
     */
    package com.demo.controller;
    
    import java.io.File;
    import java.io.IOException;
    import java.nio.file.Files;
    import java.nio.file.Path;
    import java.nio.file.Paths;
    import java.util.ArrayList;
    import java.util.Arrays;
    import java.util.List;
    
    import javax.servlet.http.HttpServletRequest;
    
    import org.apache.log4j.Logger;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.core.io.ByteArrayResource;
    import org.springframework.http.HttpHeaders;
    import org.springframework.http.HttpRequest;
    import org.springframework.http.HttpStatus;
    import org.springframework.http.InvalidMediaTypeException;
    import org.springframework.http.MediaType;
    import org.springframework.http.ResponseEntity;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.RequestPart;
    import org.springframework.web.bind.annotation.ResponseBody;
    import org.springframework.web.bind.annotation.RestController;
    import org.springframework.web.multipart.MultipartFile;
    import org.springframework.web.multipart.MultipartResolver;
    
    import com.demo.entity.Atchmnt;
    import com.demo.environment.DemoEnvironment;
    import com.demo.service.AttachmentService;
    import com.demo.util.Base64Util;
    
    /**
     * @author Denis
     *
     */
    @RequestMapping(value = "/")
    @RestController
    public class RestUploadController {
        private final Logger log = Logger.getLogger(this.getClass());
    
        DemoEnvironment env = new DemoEnvironment();
    
        @Autowired
        private AttachmentService attachmentService;
    
        @Autowired
        private MultipartResolver multipartResolver;
    
        // private String uploadFolder = "c://temp//"; // this needs to be in
        // the application.properties file.
        private String uploadFolder = env.getFilesDirectory();
    
    
        // 3.1.2 Multiple file upload
        // @PostMapping("/api/upload/multi")
    //  @Consumes(MediaType.MULTIPART_FORM_DATA_VALUE)
        @ResponseBody
        @RequestMapping(value = { "/upload/multi/{fein}" }, 
                        method = { RequestMethod.POST }, 
                        consumes = {MediaType.MULTIPART_FORM_DATA_VALUE}, 
                        produces = MediaType.APPLICATION_JSON_VALUE)
        public ResponseEntity<?> uploadFileMulti(
                @PathVariable Long fein,
                // @RequestParam("extraField") String extraField,
                @RequestPart("uploadFiles") MultipartFile[] myFiles,
                HttpServletRequest req
                ) {
    
            log.info("Multiple file upload!");
    
            // Get file name
            // String uploadedFileName = Arrays.stream(uploadFiles).map(x ->
            // x.getOriginalFilename())
            // .filter(x -> !StringUtils.isEmpty(x)).collect(Collectors.joining(" ,
            // "));
            //
            // if (StringUtils.isEmpty(uploadedFileName)) {
            // return new ResponseEntity("please select a file!", HttpStatus.OK);
            // }
    
            // Check for empty files.
            for (MultipartFile myFile : myFiles) {
                log.info("Attempting to upload of files=" + myFile.getOriginalFilename());
                if (myFile.isEmpty()) {
                    log.error("No file specified!");
                    return new ResponseEntity<>("No file specified!", HttpStatus.BAD_REQUEST);
                }
            }
    
            try {
    
                saveUploadedFiles( fein, Arrays.asList(myFiles));
    
            } catch (IOException e) {
                return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
            }
    
            return new ResponseEntity<>("Successfully uploaded - file(s).", HttpStatus.OK);
        }
    
        // save file
        private void saveUploadedFiles(Long fein, List<MultipartFile> files) throws IOException {
    
            for (MultipartFile file : files) {
                log.info("Attempting to upload the requested file.");
    
                if (file.isEmpty()) {
                    continue; // next pls
                }
    
                byte[] bytes = file.getBytes();
                String folderPath = createFileSystemFolder( uploadFolder + "/" + fein );
                log.info("saving file=" + file.getOriginalFilename());
                Path path = Paths.get(folderPath + file.getOriginalFilename());
                Files.write(path, bytes);
            }
        }
    
        public String createFileSystemFolder(String folderPath) {
            log.info("createFileSystemFolder(): attempting to create folder=" + folderPath );
            File file = new File(folderPath);
            if (!file.exists()) {
                file.mkdirs();
            } else {
                log.error("createFileSystemFolder(): failed to create the folder.");
            }
            return folderPath + "/";
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-22
      • 2017-03-23
      • 1970-01-01
      • 2019-05-06
      • 2012-02-16
      • 1970-01-01
      • 2020-02-07
      • 1970-01-01
      相关资源
      最近更新 更多