Content-Type 'multipart/form-data; border=charset=UTF-8' не поддерживается] при использовании MultipartfileJAVA

Программисты JAVA общаются здесь
Ответить Пред. темаСлед. тема
Anonymous
 Content-Type 'multipart/form-data; border=charset=UTF-8' не поддерживается] при использовании Multipartfile

Сообщение Anonymous »

Я пытаюсь загрузить изображение пользователя с помощью процесса MultipartFile, но всегда получаю одно и то же сообщение об ошибке: «charset=UTF-8» не поддерживается... Я пробовал много аннотаций, таких как @PostMapping(path="/new ", Consumer={MediaType.APPLICATION_JSON_UTF8_VALUE}) и другие решения, которые я нашел здесь, в SOF, но ничего не работает!
Может быть в этом случае конфигурация Spring Security ошибочна (я предположим нет) ? ... Я запускаю базовый зеркальный проект без Spring Security, и он работает...
Я запускаю тесты с помощью Postman
Postman
Кажется, что весь запрос, сделанный с помощью Body/form-data, отклонен, но если я запущу его с помощью Body/raw/json (без файла), все пройдет отлично!
** пользователь сущность **
@Entity
@Table(name="user", uniqueConstraints = {
@UniqueConstraint(columnNames = "username"),
@UniqueConstraint(columnNames = "email")
})
public class User {
@Id
@Column(name="id")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long Id;
@Column(name="username")
private String username;
@Column(name="password")
private String password;
@Column(name="avatar")
private String avatar;
@Column(name="email")
private String email;
@Column(name="bio")
private String bio;
@Column(name = "created_at")
private Date createdAt;
@Column(name="updated_at")
private Date updatedAt;
@ManyToMany(fetch = FetchType.LAZY)
@JsonIgnore
@JoinTable(name="user_role",
joinColumns = @JoinColumn(name="user_id"),
inverseJoinColumns = @JoinColumn(name="role_id"))
private Set roles = new HashSet();
@OneToMany(mappedBy = "donor", cascade = CascadeType.ALL)
@JsonIgnore
// liste des donations par donateurs
private Set donationsByDonor = new HashSet();
@OneToMany(mappedBy = "beneficiary", cascade = CascadeType.ALL)
@JsonIgnore
// liste des donations par bénéficiaire
private Set donationsByBeneficiary = new HashSet();
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
// liste des evaluations par user
private Set evaluations = new HashSet();
@OneToMany(mappedBy = "author", cascade = CascadeType.ALL)
@JsonIgnore
// Liste des pdfs par user
private Set
pdfs = new HashSet();
@OneToMany(mappedBy = "user", cascade = CascadeType.ALL)
@JsonIgnore
// liste des recherches par user
private Set searches = new HashSet();
@OneToMany(mappedBy = "alertLauncher", cascade = CascadeType.ALL)
@JsonIgnore
// liste alerts par user
private Set alertList = new HashSet();

public User() {
}

public User(String username, String password) {
this.username = username;
this.password = password;
}

public User(String username, String email, String password, String avatar) {
this.username = username;
this.email = email;
this.password = password;
this.avatar = avatar;
}

public User(String username, String password, String avatar, String email, String bio, Date createdAt, Date updatedAt, Set roles, Set donationsByBeneficiary, Set donationsByDonor, Set evaluations, Set pdfs, Set searches, Set alertList) {
this.username = username;
this.password = password;
this.avatar = avatar;
this.email = email;
this.bio = bio;
this.createdAt = createdAt;
this.updatedAt = updatedAt;
this.roles = roles;
this.donationsByBeneficiary = donationsByBeneficiary;
this.donationsByDonor = donationsByDonor;
this.evaluations = evaluations;
this.pdfs = pdfs;
this.searches = searches;
this.alertList = alertList;
}

public Long getId() {
return Id;
}

public void setId(Long id) {
Id = id;
}

public String getUsername() {
return username;
}

public void setUsername(String username) {
this.username = username;
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}

public String getAvatar() {
return avatar;
}

public void setAvatar(String avatar) {
this.avatar = avatar;
}

public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}

public String getBio() {
return bio;
}

public void setBio(String bio) {
this.bio = bio;
}

public Date getCreatedAt() {
return createdAt;
}

public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}

public Date getUpdatedAt() {
return updatedAt;
}

public void setUpdatedAt(Date updatedAt) {
this.updatedAt = updatedAt;
}

public Set getRoles() {
return roles;
}

public void setRoles(Set roles) {
this.roles = roles;
}

public Set getDonationsByDonor() {
return donationsByDonor;
}

public void setDonationsByDonor(Set donationsByDonor) {
this.donationsByDonor = donationsByDonor;
}

public Set getDonationsByBeneficiary() {
return donationsByBeneficiary;
}

public void setDonationsByBeneficiary(Set donationsByBeneficiary) {
this.donationsByBeneficiary = donationsByBeneficiary;
}

public Set getEvaluations() {
return evaluations;
}

public void setEvaluations(Set evaluations) {
this.evaluations = evaluations;
}

public Set getPdfs() {
return pdfs;
}

public void setPdfs(Set pdfs) {
this.pdfs = pdfs;
}

public Set getSearches() {
return searches;
}

public void setSearches(Set searches) {
this.searches = searches;
}

public Set getAlertList() {
return alertList;
}

public void setAlertList(Set alertList) {
this.alertList = alertList;
}
}

**Dto от клиента **
@Data
public class UserDTOWayIN {
String username;
String password;
String avatar;
String email;
String bio;
Date createdAt;
Date updatedAt;
Set roles;
}

**Передача клиенту **
@Data
public class UserDTO {
Long Id;
String username;
String bio;
Date createdAt;
Date updatedAt;
Set roles;
}

**UserController с конечной точкой регистрации **
@CrossOrigin(origins = "http://localhost:4200", maxAge = 3600)
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService service;
@Autowired
private ModelMapper modelMapper;
public static String uploadDirectory = System.getProperty("user.dir")+"/src/main/webapp/avatars/";

@PostMapping(path="/new", consumes={MediaType.APPLICATION_JSON_UTF8_VALUE})
@PreAuthorize("hasRole('ADMIN'), hasRole('USER')")
public ResponseEntity saveUser(@ModelAttribute UserDTOWayIN clientDatas, @RequestParam("file")MultipartFile file) throws IOException {
String originalFilename = file.getOriginalFilename();
Path fileNameAndPath= Paths.get(uploadDirectory, originalFilename);
Files.write(fileNameAndPath, file.getBytes());
clientDatas.setAvatar(originalFilename);
// Conversion des datas front en DTOWayIN
UserDTOWayIN userDTOWayIN = modelMapper.map(clientDatas, UserDTOWayIN.class);
// Conversion sens DTOWayIN à Entité
User user = service.saveUser(userDTOWayIN);
// Conversion sens Entité à DTO
UserDTO userDTO = modelMapper.map(user, UserDTO.class);
return new ResponseEntity(userDTO, HttpStatus.CREATED);
}


Подробнее здесь: https://stackoverflow.com/questions/779 ... orted-when
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «JAVA»