英文:
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?
ExcelController:
@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);
}
}
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("/api/v1/signup");
}
}
// 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论