mysql - 文件上传 Angular - spring boot - mysql

标签 mysql angular spring-boot

我有一个工作发布 API,将表单数据发送到后端并将其发布到数据库。 当我将输入文件类型添加到表单并将其附加到数据表单时,出现错误。

我总是遇到这个错误:

"error: "Internal Server Error"
message: "Unrecognized field "file" (class org.sid.model.User), not marked as ignorable (6 known properties: "fileName", "id", "email", "name", "password", "logo"])↵ at [Source: (String)"{"name":"ss","email":"sss","password":"ssssssss","file":"C:\fakepath\ooredoo_758118.png"}"; line: 1, column: 58] (through reference chain: org.sid.model.User["file"])" path: "/users" "

Controller

@CrossOrigin(origins = { "http://localhost:4200", "http://localhost:9000" }, maxAge = 36000)
/*@RequestMapping(value="/users" , method=RequestMethod.POST)*/
@RequestMapping(value="/users" , headers = ("content-type=multipart/*"), method = RequestMethod.POST,
consumes = MediaType.MULTIPART_FORM_DATA_VALUE ,
        produces = { "application/json" }
)
public User save(@RequestPart("file") MultipartFile f  ,
        @RequestPart ("user") String u) 
        throws JsonParseException, JsonMappingException, IOException{
    User user = new ObjectMapper().readValue(u, User.class) ;
    user.setLogo(f.getBytes());
    return userRepository.save(user);

    }

User.java

@Entity
public class User { 
@Id @GeneratedValue
private Long id ;
private String name ;
private String email ;
private String password ;
@Column(name="logo")
private byte[] logo;
@Column(name="file_name")
private String fileName ;

}

ma​​inApplication.java

@SpringBootApplication
public class MyChebbaApplication {
    public static void main(String[] args) {
        SpringApplication.run(MyChebbaApplication.class, args);
    }   
    @Bean
    public MultipartConfigElement multipartConfigElement() {
        MultipartConfigFactory factory = new MultipartConfigFactory();
        factory.setMaxFileSize("10240KB");
        factory.setMaxRequestSize("10240KB");
        return factory.createMultipartConfig();
    }


}

客户端

组件.html

 <div class="container" >
  <div class="row">
    <div class="col-md-8 col-md-offset-2">
      <div class="panel panel-default">
          <div class="panel-heading">Register</div>
          <div class="panel-body">
              <form class="form-horizontal" #form="ngForm" (ngSubmit)="onSubmit(form)">

                  <div class="form-group">
                      <label for="name" class="control-label col-md-4">Nom Complet</label>

                      <div class="col-md-6">
                        <input id="name" type="text" name="name" #userName="ngModel" ngModel class="form-control" required>
                      </div>
                    </div>

                    <div class="form-group">
                        <label for="email" class="control-label col-md-4">E-mail Address</label>

                        <div class="col-md-6">
                          <input id="email" type="email" name="email" #userEmail="ngModel" ngModel class="form-control" required>
                        </div>
                      </div>


                      <!-- <div class="form-group">
                          <label for="phone" class="control-label col-md-4">Phone number</label>

                          <div class="col-md-6">
                            <input id="phone" type="phone" name="phone" #phone="ngModel" ngModel class="form-control" >
                          </div>
                        </div> -->


                      <div class="form-group">
                          <label for="password" class="control-label col-md-4">Password</label>

                          <div class="col-md-6">
                            <input id="password" type="text" name="password" #password="ngModel" ngModel class="form-control" required>
                          </div>
                        </div>

                      <div class="form-group">
                          <label for="file" class="control-label col-md-4">File Upload</label>

                          <div class="col-md-6">
                            <input 
                             type="file" 
                            name="file"  
                            accept="image/*"
                            (change)="onFileSelected($event)" 
                            ngModel class="form-control" >
                          </div>
                        </div>              

                  <div class="form-group">
                          <div class="col-md-8 col-md-offset-4">
                            <button type="submit" class="btn btn-primary"
                              [disabled]="form.invalid">
                              Register
                            </button>
                          </div>
                        </div>



              </form>
          </div>
      </div>
    </div>
</div>
</div>

组件.ts

    selectedFile: File = null ;


  constructor(private userService: UserService) { }

  ngOnInit() {
  }

onFileSelected(event) {
  console.log(event) ;
this.selectedFile = event.target.files[0] ;
}


  onSubmit(form: any) {
    let fd = new FormData() ;
    const user = form.value ;
    fd.append('user' , JSON.stringify(user)) ;
    fd.append('file' , this.selectedFile ) ;
    console.log(fd) ;
    this.userService.register(fd  )
      .then((resp) => {
        this.userService.logUserIn(resp) ;
      }) ;
  }

user.service.ts

   register(fd: FormData ): Promise<UserData> {
    return this.http.post(`${CONFIG.API_URL}/users`, fd)
                    .toPromise()
                    .then((response) => {
                        let token = response.json().token ;
                            let user = response.json() ;

                            let userData = new UserData(token, user) ;
                            this.router.navigate(['/users']);
                            return userData ;
                    });

}

最佳答案

这意味着您的 JSON 字符串 u 不包含"file"字段。为了忽略缺失的字段,请使用:

ObjectMapper mapper = new ObjectMapper()
                      .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) 

mapper.readValue(u, User.class);

...

祝你好运。

关于mysql - 文件上传 Angular - spring boot - mysql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53654484/

相关文章:

php - 找不到数据库?

MySQL SUM 多列

javascript - 了解 Angular 2 webpack 项目中的源代码符号链接(symbolic link)

angular - 找不到模块 : Error: Can't resolve './$$_gendir/app/app.module.ngfactory'

css - 从 Thymeleaf 中的模型对象设置 CSS 变量

java - Spring boot 应用程序无法在 PUT API 调用中映射 List 对象

php - 需要将选择 ID 作为表单的一部分提交,我该怎么做?

php - 如何从 MYSQL 数据库分配的 PHP session 数组中打印单个变量

javascript - 如何为 ngrx/store 2.2.1 配置 system-config.js

java - 向模型添加验证后出现 Spring Boot 异常