404发送multipart / form-data java + angularjs时无法发布

时间:2016-09-19 14:45:39

标签: java angularjs multipartform-data jcr jackrabbit

我正在尝试在我的应用程序中实现图片上传。在后端,我使用java + spring和jackrabbit存储库。我已经检查了Postman的功能并且它正在工作。  这是java代码:

**

JcrController:

**

@RestController
@RequestMapping(value = "files")
public class JcrController {

    private static final Logger LOGGER = LoggerFactory.getLogger(JcrController.class);

    @Autowired
    private JcrService jcrService;

    @RequestMapping(method = RequestMethod.POST)
    public ResponseEntity handleFileUpload(@RequestParam("file") MultipartFile file) {
        if (!file.isEmpty()) {
            try {
                this.jcrService.uploadFile(file);
                return new ResponseEntity(HttpStatus.OK);
            } catch (RepositoryException | IOException e) {
                LOGGER.debug(e.toString());
            }
        }
        return new ResponseEntity(HttpStatus.BAD_REQUEST);
    }

    @RequestMapping(value = "/{name}", method = RequestMethod.GET)
    public ResponseEntity getContent(@PathVariable String name) throws Exception {
        return new ResponseEntity<>(IOUtils.toByteArray(this.jcrService.getContent(name)), HttpStatus.OK);
    }
}

**

JcrService:

**

@Service
public class JcrService {
    private static final Logger LOGGER = LoggerFactory.getLogger(JcrService.class);

    private Repository repository;

    @Autowired
    public JcrService(MyJcrUtils myJcrUtils) {
        try {
            this.repository = new URLRemoteRepository(myJcrUtils.getUri());
        } catch (MalformedURLException e) {
            LOGGER.error(" ***** Failed to obtain Content Repository Session --> " + e.getMessage());
            LOGGER.error(" ******** Shutting down all Content Repository Services ********* ");
        }
    }

    public void uploadFile(MultipartFile multipartFile) throws RepositoryException, IOException {
        Session session = repository.login(new SimpleCredentials("admin", "admin".toCharArray()));
        try {
            String extensionRemoved = multipartFile.getOriginalFilename().split("\\.")[0];
            File convFile = new File(extensionRemoved);
            convFile.createNewFile();
            multipartFile.transferTo(convFile);
            Node folder = session.getRootNode();
            Node file = folder.addNode(convFile.getName(), "nt:file");
            Node content = file.addNode("jcr:content", "nt:resource");
            Binary binary = session.getValueFactory().createBinary(new BufferedInputStream(new FileInputStream(convFile)));
            content.setProperty("jcr:data", binary);
            content.setProperty("jcr:mimeType", "image/gif");
            session.save();
        } finally {
            session.logout();
        }
    }

    public InputStream getContent(String name) throws Exception {
        Session session = repository.login(
                new SimpleCredentials("admin", "admin".toCharArray()));
        Node folder = session.getRootNode();
        Node file = folder.getNode(name);
        Node content = file.getNode("jcr:content");
        return JcrUtils.readFile(content);
    }
}

在前端,我有服务负责发送请求,这是方法:

**

卡types.service.js:

**

uploadFile(file) {
    let fd = new FormData();
    let fo=fd;
    fd.append('file', file);

    return this.$http.post(`/jc-repository/files`, fd, {
        transformRequest: angular.identity,
        headers: {'Content-Type': undefined}
    }).then((response)=> {
        this.toastService.showSuccessToast("Utworzono pomyslnie nowy typ kartki!");
        return response.data;
    }).catch((response)=> {
        this.toastService.showWarningToast(response.statusText);
    });
}

**

请求标头:

** image link

在双方调试(后端和前端)时,我发现当角度执行POST时,它甚至没有进入JcrController上的断点(当在Postman中执行POST时它会在断点处停止),所以我认为我在uploadFile()方法上做错了,但我不知道是什么。

如果您有任何想法,我将非常感谢您的回答。谢谢!

PS。我使用webpack,ECMAScript 6和angular 1.5.8

PS2。 我比较了邮递员的请求和角度的请求,我看不出差异。

这是来自postman(我使用tcpmonitor插件为intellij:

POST /jc-repository/files HTTP/1.1
Host: 127.0.0.1
Connection: keep-alive
Content-Length: 3612
Postman-Token: 21b4635d-2246-169e-70cc-bf3c1fe0c410
Cache-Control: no-cache
Origin: chrome-extension://fhbjgbiflinjbdggehcddcbncdddomop
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.116 Safari/537.36
Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryFmVqum2mqB5F1jI7
Accept: */*
Accept-Encoding: gzip, deflate
Accept-Language: pl-PL,pl;q=0.8,en-US;q=0.6,en;q=0.4

------WebKitFormBoundaryFmVqum2mqB5F1jI7
Content-Disposition: form-data; name="file"; filename="google.jpg"
Content-Type: image/jpeg

这是来自chrome:

Request URL:http://localhost:8060/jc-repository/files
Request Method:POST
Status Code:404 Not Found
Remote Address:127.0.0.1:8060
Accept:*/*
Accept-Encoding:gzip, deflate
Accept-Language:pl-PL,pl;q=0.8,en-US;q=0.6,en;q=0.4
Cache-Control:no-cache
Connection:keep-alive
Content-Length:3612
Content-Type:multipart/form-data; boundary=----WebKitFormBoundaryBijlqUbjGbJIGJBo
Host:localhost:8060
Origin:http://localhost:8060
Pragma:no-cache
Referer:http://localhost:8060/add-card-type
User-Agent:Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.116 Safari/537.36
X-AUTH-TOKEN:eyJhbGciOiJIUzUxMiJ9.eyJzdWIiOiJhZG1pbnBncyIsImF1ZGllbmNlIjoid2ViIiwiY3JlYXRlZCI6MTQ3NDM2NzkxNjA4MiwiZXhwIjoxNDc0NDU0MzE2fQ.Ur1fHo9VkfHBPPxF665LZryqUQqCRFZyAppI4J_Rt0PCda8Vai_bwHBxKp89yF1Fc34rGbBpZkCI-CW9r-T2SA
Request Payload
------WebKitFormBoundaryBijlqUbjGbJIGJBo
Content-Disposition: form-data; name="file"; filename="google.jpg"
Content-Type: image/jpeg


------WebKitFormBoundaryBijlqUbjGbJIGJBo--

0 个答案:

没有答案