简体   繁体   中英

upload file spring boot and angular

who can help me solve this problem please

org.apache.tomcat.util.http.fileupload.FileUploadException: the request was rejected because no multipart boundary was found

FileController.java

package com.example.fileUploadApi.controller;
import org.apache.cxf.jaxrs.ext.multipart.MultipartBody;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;

@RestController
@RequestMapping(path = "/fileUpload")
@CrossOrigin(origins = "http://localhost:4200")
@Produces(MediaType.APPLICATION_JSON)
public class FileController 
{
    @POST
    @Path("/upload")
    public  void uploadData(MultipartBody file) throws Exception {
        System.out.println(file);
    }
}

upload-file.component.html

<div>
   <input type="file" change="uploadFile($event)"  />
</div>
 

UploadFileComponent.ts

uploadFile(event) {
file = event.target.files[0]
  const formData = new FormData();
  const dali = {
       a: 'dali'
   };
  formData.append('file', file);
  formData.append('model', JSON.stringify(dali));
  this.fileUploadService.upload(formData).subscribe(
    rsp => {console.log(rsp.type);}
}

Pass you formData as 'params' in the service and fetch it in the API using @RequestParams. I don't see @RequestParams in the POST call.

Use this code in your spring boot project this will work 100%

@PostMapping("/process-contact")
    public String setContactForm(@Valid @ModelAttribute("contact") Contact contact,
            @RequestParam("profileImage") MultipartFile file, Principal principal, Model model, BindingResult rs) {

        if (rs.hasErrors()) {
            model.addAttribute("contact", contact);
            model.addAttribute("warning", rs.getFieldError());

            return "user/home";

        }

        User user = this.userRepositery.findUserByUserEmail(principal.getName());

        try {

            if (file.isEmpty()) {
                contact.setImage("1.png");
            } else {

                String saveImagePath = "UCNT" + new Date().getTime() + file.getOriginalFilename();

                File saveDirectory = new ClassPathResource("static/img/contact").getFile();

                Path path = Paths.get(saveDirectory.getAbsolutePath() + File.separator + saveImagePath);

                contact.setImage(saveImagePath);

                Files.copy(file.getInputStream(), path, StandardCopyOption.REPLACE_EXISTING);

            }

            contact.setUser(user);

            user.getContacts().add(contact);

            this.userRepositery.save(user);
            model.addAttribute("user", user);

            model.addAttribute("message", "Contact has added successfully.");

        } catch (Exception e) {
            System.out.println(e);
            e.printStackTrace();
            model.addAttribute("warning", "Somthing went wrong try again.");

        }

        return "user/add-contact";
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM