springcloud feign upload files

Recently with springcloud upload files, end consumers and the service provider by calling feign, a little step on the middle point of the pit, now the final executable code release out:

 

Forewarned, here base64 encoded image file is saved individual needs, those related to the code, you can ignore, only concerned with the relevant code can upload files.

      If the incoming page changed to base64 encoded base64 encoding incoming or consumer side, is passed in feign underlying service interfaces can be received directly by the String parameter.

        <! - Feigh uploadFile ->

        <dependency>

            <groupId>io.github.openfeign.form</groupId>

            <artifactId>feign-form</artifactId>

            <version>3.5.0</version>

        </dependency>

        <dependency>

            <groupId>io.github.openfeign.form</groupId>

            <artifactId>feign-form-spring</artifactId>

            <version>3.5.0</version>

        </dependency>

        <dependency>

            <groupId>commons-fileupload</groupId>

            <artifactId>commons-fileupload</artifactId>

            <version>RELEASE</version>

        </dependency>

 

Version dependency: springboot version 2.1.3.RELEASE version, springcloud the latest version of GreenWich

 

2. The service provider implementation class code between layers, which is converted into bytecode base64 saved to the sample database.

Some code is not too full

@ slf4j

@Service

@RestController

@Transactional(rollbackFor = Exception.class)

@Api (position = 22, tags = { "ApplicationService"}, description = "application management services provide CRUD operations such as management interface")

public class ApplicationServiceImpl  implements ApplicationService {

 

    @Autowired

    private ApplicationDao applicationDao;

  @Override

    public String saveLogoById(@NonNull String id, @NonNull MultipartFile logo) {

        if (StringUtils.isBlank(id)) {

            throw new IllegalArgumentException("appId must be not empty.");

        }

        byte[] prefix="data:image/png;base64,".getBytes();

        byte[] _logo = new byte[0];

        try {

            _logo= Base64.encodeBase64(logo.getBytes());

        } catch (Exception e) {

            throw new RuntimeException(e);

        }

        byte[] mylogo=new byte[prefix.length+_logo.length];

        System.arraycopy(prefix, 0, mylogo, 0, prefix.length);

        System.arraycopy(_logo, 0, mylogo, prefix.length, _logo.length);

        applicationDao.logoSaveById(id, mylogo);

        return id;

    }

 

    @Override

    public ResponseEntity<byte[]> getLogoById(@NonNull String id) {

        byte[] logo = ((ApplicationDao) this._getBaseDao()).logoGetById(id);

        return new ResponseEntity<>(logo, HttpStatus.OK);

    }

}

 

dao in the preservation obtain no different.

The wording xml

<update id="logoSave" parameterType="hashmap">
UPDATE ECS_APP SET APP_LOGO=#{logo},APP_UPDATED_AT = CURRENT_TIMESTAMP(3) WHERE APP_ID = #{id}
</update>

 

3. If at the base64 encoded string passed as direct, as well.

 

4.feign client interface:

@FeignClient(value = "ecs", contextId = "ApplicationService" ,configuration = FeignMultipartSupportConfig.class)

@RequestMapping(value = "/ApplicationService")

public interface ApplicationService {

    @PostMapping(value = "/saveLogoById",produces = {MediaType.APPLICATION_JSON_VALUE},  consumes = MediaType.MULTIPART_FORM_DATA_VALUE)

    @ApiOperation (position = 62, value = "Saves the specified ID applications trademark", notes = "If you save is not successful, throws an exception")

    @ApiImplicitParams(value = {

            @ApiImplicitParam(paramType = "query", name = "id", required = true, dataType = "string", value = "应用ID"),

    // no logo here

    })

    String saveLogoById(@ApiIgnore @NonNull @RequestParam(value = "id") String id, @ApiIgnore @NonNull @RequestPart(value = "logo") MultipartFile logo);

 

    @PostMapping(value = "/getLogoById", produces = {MediaType.APPLICATION_JSON_VALUE})

    @ApiOperation (position = 61, value = "Gets the ID of the trademark application", produces = MediaType.APPLICATION_JSON_VALUE, notes = "if the acquisition succeeds, the return trademarks, unbranded returns null, for other reasons if the application does not exist or is thrown abnormal")

    @ApiImplicitParams(value = {

            @ApiImplicitParam(paramType = "query", name = "id", required = true, dataType = "string", value = "应用ID"),

    })

    ResponseEntity<byte[]> getLogoById(@ApiIgnore @NonNull @RequestParam(value = "id") String id);

}

 

 

    @FeignClient (value = "ecs", contextId = "ApplicationService", configuration = FeignMultipartSupportConfig.class) FeignMultipartSupportConfig exemplary class code here

import feign.codec.Encoder;
import feign.form.spring.SpringFormEncoder;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cloud.openfeign.support.SpringEncoder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class FeignMultipartSupportConfig {
    @Autowired
private ObjectFactory<HttpMessageConverters> messageConverters;

@Bean
public Encoder feignFormEncoder() {
        return new SpringFormEncoder(new SpringEncoder(messageConverters));
}

    @Bean
public feign.Logger.Level multipartLoggerLevel() {
        return feign.Logger.Level.FULL;
}


}

 

The consumer side test code:

 

@PostMapping(value = "/testLogo")

    @ApiOperation (position = 62, value = "test Logo", response = Map.class, notes = "If you save is not successful, throws an exception")

    public boolean testLogo(){

        File file = new File("E:\\haha.png");

        DiskFileItem fileItem = (DiskFileItem) new DiskFileItemFactory().createItem("logo",

                MediaType.TEXT_PLAIN_VALUE, true, file.getName());

        try (InputStream input = new FileInputStream(file);

             OutputStream os = fileItem.getOutputStream()) {

            IOUtils.copy(input, os);

        } catch (Exception e) {

            throw new IllegalArgumentException("Invalid file: " + e, e);

        }

        MultipartFile logo = new CommonsMultipartFile(fileItem);

        log.info(applicationService.saveLogoById("20190520132707572-1007-CD574C23C",logo));

        return true;

}

 

Note that there is a pit, createItem ( "logo", the name of each feign here must be the same in the parameter name, or feign not be passed in this parameter when you call. No consumer side logo parameter value.

 

6. consumer side formal Code:

SLF4J @
 @RestController @RequestMapping ( "/ App" )
 @Api ( Tags = { "the ApplicationController" } , Description = "application management services" )

 

@PostMapping ( value = "/ saveLogo" )
 @ApiOperation ( position = 62 , value = "Saves the specified ID applications trademark" , the Response = the Map. Class, Notes = "If you save is not successful, throws an exception" )
 @ApiImplicitParams ( value = {
         @ApiImplicitParam ( paramType = "Query" , name = "for appId" , required = to false, dataType = "String" , value= "应用ID"),
})
public String saveLogo(@RequestPart(value = "logo") MultipartFile logo, String appId) {
    if (StringUtils.isBlank(appId)) {
        Application application = new Application();
application.setName("onlysavelogo_"+RandomStringUtils.random(30));
application.setEntId(AccessIdentity.getEnterpriseId());
appId = applicationService.create (file application) ;
 }
     return ApplicationService .saveLogoById (for appId , logo) ;
 } @PostMapping ( value = "/ getLogoById" )
 @ApiOperation ( position = 61 is , value = "acquires the specified application ID mark" , Produces = the MediaType. APPLICATION_JSON_VALUE , Notes = "if the acquisition succeeds, the return trademarks, unbranded returns null, for other reasons, or if the application does not exist, an exception is thrown" )
 @ApiImplicitParams ( value = {
         @ApiImplicitParam (

paramType = "query", name = "appId", required = true, dataType = "string", value = "应用ID")
})
public ResponseEntity<byte[]> getLogoById(@NonNull String appId) {
    return applicationService.getLogoById(appId);
}

}

 

Incoming calls while pictures and objects

 

@PostMapping ( value = "/ addApplicationInfo" )
 @ApiOperation ( position = 62 , value = "save complete application information (application and picture)" , the Response = the Map. Class, Notes = "If you save is not successful, throws an exception" )
 @ApiImplicitParams ( value = {
       // @ApiImplicitParam (paramType = "Query", name = "for appId", = required to false, dataType = "String", value = "application ID"
)
})
public String addApplicationInfo(@RequestPart(value = "logo") A MultipartFile logo , @NonNull ApplicationVo applicationVo) {
     // this code is used simultaneously Upload logo

 }

 

So here you can receive parameters.

 

After testing is not a problem.

 

 

 

Guess you like

Origin fsh430623.iteye.com/blog/2441555