AngularJS image upload with Java server

2

I'm having a problem uploading a web image, I'm using the angular file upload , when I upload it it writes the image to the Frame - > images of the browser, and when I read the inputStream there on my server it does not return the image. How do I solve the problem?

    
asked by anonymous 29.01.2014 / 13:21

1 answer

1

I think there is a misunderstanding in your code. First you retrieve an item like this:

FileItemStream item = iterator.next();

Then, when reading the bytes of the file, you retrieve the InputStream of the request:

while ((read = req.getInputStream().read(bytes)) != -1) { ... }

However, the code should retrieve the InputStream of the item, like this:

InputStream inputStream = item.openStream();
while ((read = inputStream.read(bytes)) != -1) { ... }

After all, the request could have more fields and files, right?

Anyway, I have slightly refuted the code you posted in the comments and I came to this:

if (ServletFileUpload.isMultipartContent(req)) {

    FileItemFactory fileItemFactory = new DiskFileItemFactory();
    ServletFileUpload upload = new ServletFileUpload(fileItemFactory);
    FileItemIterator iterator = upload.getItemIterator(req);
    while (iterator.hasNext()) {

        FileItemStream item = iterator.next();
        if (item.getName() != null) {

            File uploadedFile = new File(path + "/" + item.getName());

            byte[] bytes = new byte[2048];
            int read = 0;
            OutputStream outpuStream = new FileOutputStream(new File(uploadedFile.getAbsolutePath()));
            InputStream inputStream = item.openStream();
            while ((read = inputStream.read(bytes)) != -1) {
                outpuStream.write(bytes, 0, read);
            }
            outpuStream.close();
        }

    }

}
    
29.01.2014 / 15:07