How can I upload an excel file with Spring Boot and Postman to a MySQL Database? – Status: 401 Unauthorized

huangapple go评论78阅读模式
英文:

How can I upload an excel file with Spring Boot and Postman to a MySQL Database? - Status: 401 Unauthorized

问题

ExcelController:

@CrossOrigin("http://localhost:8081")
@Controller
@RequestMapping("/api/excel")
public class ExcelController {

  @Autowired
  ExcelService fileService;

  @PostMapping("/upload")
  public ResponseEntity<ResponseMessage> uploadFile(@RequestParam("file") MultipartFile file) {
    String message = "";

    if (ExcelHelper.hasExcelFormat(file)) {
      try {
        fileService.save(file);

        message = "Uploaded the file successfully: " + file.getOriginalFilename();
        return ResponseEntity.status(HttpStatus.OK).body(new ResponseMessage(message));
      } catch (Exception e) {
        message = "Could not upload the file: " + file.getOriginalFilename() + "!";
        return ResponseEntity.status(HttpStatus.EXPECTATION_FAILED).body(new ResponseMessage(message));
      }
    }

    message = "Please upload an excel file!";
    return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseMessage(message));
  }

  @GetMapping("/tutorials")
  public ResponseEntity<List<Tutorial>> getAllTutorials() {
    try {
      List<Tutorial> tutorials = fileService.getAllTutorials();

      if (tutorials.isEmpty()) {
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
      }

      return new ResponseEntity<>(tutorials, HttpStatus.OK);
    } catch (Exception e) {
      return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
    }
  }

  @GetMapping("/download")
  public ResponseEntity<Resource> getFile() {
    String filename = "tutorials.xlsx";
    InputStreamResource file = new InputStreamResource(fileService.load());

    return ResponseEntity.ok()
        .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + filename)
        .contentType(MediaType.parseMediaType("application/vnd.ms-excel"))
        .body(file);
  }
}

WebSecurityConfig:

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Bean
    public UserDetailsService userDetailsService() {
        return new UserDetailsServiceImpl();
    }

    @Bean
    public BCryptPasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Bean
    public DaoAuthenticationProvider authenticationProvider() {
        DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
        authProvider.setUserDetailsService(userDetailsService());
        authProvider.setPasswordEncoder(passwordEncoder());

        return authProvider;
    }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.authenticationProvider(authenticationProvider());
    }
    
    @Override
    public void configure(WebSecurity web) throws Exception {
        web.ignoring().antMatchers("/api/v1/signup");
    }
}

application.properties:

spring.jpa.hibernate.ddl-auto = update
spring.datasource.url=jdbc:mysql://${MYSQL_HOST:localhost}:3306/db_faq4?useSSL=false
spring.datasource.username = root
spring.datasource.password =
spring.jpa.properties.hibernate.dialect= org.hibernate.dialect.MySQL5InnoDBDialect
spring.servlet.multipart.enabled=true
spring.servlet.multipart.max-file-size=5MB
spring.servlet.multipart.max-request-size=10MB
spring.mvc.dispatch-options-request=true

You can find the whole source code on GitHub as well: https://github.com/bezkoder/spring-boot-upload-excel-files

英文:

I'm working on a RESTful FAQ Webservice. So I decided to implement a import/download feature for excel files. Currently I'm focussing more on the upload feature. So to implement this feature I followed a Tutorial (https://bezkoder.com/spring-boot-upload-excel-file-database/) because I'm a newbie in Spring Boot or in programming in general.

So now if I want to upload my example Excel File there is actually no respond from Postman. You can see it in the picture below. Aswell Postman says Status: 401 Unauthorized. What does this mean and how can I fix that?

How can I upload an excel file with Spring Boot and Postman to a MySQL Database? – Status: 401 Unauthorized

ExcelController:

@Controller
@RequestMapping(&quot;/api/excel&quot;)
public class ExcelController {
@Autowired
ExcelService fileService;
@PostMapping(&quot;/upload&quot;)
public ResponseEntity&lt;ResponseMessage&gt; uploadFile(@RequestParam(&quot;file&quot;) MultipartFile file) {
String message = &quot;&quot;;
if (ExcelHelper.hasExcelFormat(file)) {
try {
fileService.save(file);
message = &quot;Uploaded the file successfully: &quot; + file.getOriginalFilename();
return ResponseEntity.status(HttpStatus.OK).body(new ResponseMessage(message));
} catch (Exception e) {
message = &quot;Could not upload the file: &quot; + file.getOriginalFilename() + &quot;!&quot;;
return ResponseEntity.status(HttpStatus.EXPECTATION_FAILED).body(new ResponseMessage(message));
}
}
message = &quot;Please upload an excel file!&quot;;
return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(new ResponseMessage(message));
}
@GetMapping(&quot;/tutorials&quot;)
public ResponseEntity&lt;List&lt;Tutorial&gt;&gt; getAllTutorials() {
try {
List&lt;Tutorial&gt; tutorials = fileService.getAllTutorials();
if (tutorials.isEmpty()) {
return new ResponseEntity&lt;&gt;(HttpStatus.NO_CONTENT);
}
return new ResponseEntity&lt;&gt;(tutorials, HttpStatus.OK);
} catch (Exception e) {
return new ResponseEntity&lt;&gt;(null, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
@GetMapping(&quot;/download&quot;)
public ResponseEntity&lt;Resource&gt; getFile() {
String filename = &quot;tutorials.xlsx&quot;;
InputStreamResource file = new InputStreamResource(fileService.load());
return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, &quot;attachment; filename=&quot; + filename)
.contentType(MediaType.parseMediaType(&quot;application/vnd.ms-excel&quot;))
.body(file);
}
}

Aswell I use Spring Security so the user needs to be logedin to see the website.

@Configuration
@EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
public UserDetailsService userDetailsService() {
return new UserDetailsServiceImpl();
}
@Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public DaoAuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
authProvider.setUserDetailsService(userDetailsService());
authProvider.setPasswordEncoder(passwordEncoder());
return authProvider;
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.authenticationProvider(authenticationProvider());
}
//    @Override
//    protected void configure(HttpSecurity http) throws Exception {
//        http.authorizeRequests()
//                .anyRequest().authenticated()
//                .and()
//                .formLogin().permitAll()
//                .and()
//                .logout().permitAll();
//    }
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().antMatchers(&quot;/api/v1/signup&quot;);
}
}
//    protected void configure(HttpSecurity http) throws Exception {
//        http.authorizeRequests()
//                .anyRequest().authenticated()
//                .and()
//                .formLogin().permitAll()
//                .and()
//                .logout().permitAll();
//    }

I commented that out so I do not get always the Login page in Postman and get the actual page.

application.properties:

spring.datasource.url=jdbc:mysql://${MYSQL_HOST:localhost}:3306/db_faq4?useSSL=false
spring.datasource.username = root
spring.datasource.password =
spring.jpa.properties.hibernate.dialect= org.hibernate.dialect.MySQL5InnoDBDialect
spring.servlet.multipart.enabled=true
spring.servlet.multipart.max-file-size=5MB
spring.servlet.multipart.max-request-size=10MB
spring.mvc.dispatch-options-request=true

So if you need more Information say what you need. You can find the whole source code on github aswell. (https://github.com/bezkoder/spring-boot-upload-excel-files)

As I said I'm a beginner in programming. So feel free to say where my problems are and how can I improve them and myself and how can I get better in asking questions on stackoverflow so its easier for you to understand my problem.

答案1

得分: 1

在您的标头中尝试传递安全令牌或凭据,如下所示:

headers.setBasicAuth("admin", "admin");

分别尝试这两种方式。应该可以正常工作。

英文:

In your header try to pass the security token or the credentials like below:

headers.setBasicAuth("admin", "admin");

Give it a try with both one by one. Should work.

huangapple
  • 本文由 发表于 2020年9月25日 22:26:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/64066047.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定