1

I'm trying to implement image upload in my application. On the backend side I'm using java+spring and jackrabbit repository. I already checked the functionality by Postman and it's working. Here is the java code:

**

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);
    }
}

On the frontend side i have service which is responsible for sending a request, here is the method:

**

card-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);
    });
}

**

Request header:

** image link

While debugging on both sides(backend and frontend) I discovered that when angular is performing POST it doesn't even go to the breakpoint on the JcrController(when performing POST in Postman it does stop on the breakpoint), so I think I'm doing something wrong at the uploadFile() method but I don't know what.

I would appreciate every answer if you have any idea. Thanks!

PS. Im using webpack, ECMAScript 6 and angular 1.5.8

PS2. I compared the request from postman and request from angular, i can't see the difference.

This is from postman(i used tcpmonitor plugin for 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

This is from 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--
2
  • what is the URL that you enter for /{name} endpoint..? Commented Sep 19, 2016 at 15:06
  • 1
    The endpont url is "/jc-repository/files" Commented Sep 19, 2016 at 15:32

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.