Table of Contents
Question content
Workaround
Home Java Unable to upload image in Spring Boot application

Unable to upload image in Spring Boot application

Feb 22, 2024 pm 12:58 PM

Having trouble uploading images in your Spring Boot application? don’t worry! PHP editor Baicao provides you with a solution. No matter what difficulty you face uploading images, you'll find the answer here. Continue reading our java Q&A to learn how to successfully upload images in a Spring Boot application. Let’s solve this problem together!

Question content

I developed a springboot application using react as the front end to upload images into a folder.

@postmapping(value = "/upload")
public responseentity<?> uploadimage(@requestparam("user") string user, @requestparam("image") multipartfile file) {
    try {
        system.out.println("-------------------------------------------------------------------");
        this.process(ioutils.tobytearray(file.getinputstream()), user, file.getoriginalfilename().substring(file.getoriginalfilename().lastindexof(".")));
    } catch (ioexception e) {
        // todo auto-generated catch block
        e.printstacktrace();
    }
    return new responseentity<>("uploaded", httpstatus.ok);//userservice.uploadimagefile(user, file);
}


@async
public void process(byte[] bs, string user, string ext) throws ioexception {

    string fname = user.substring(0, user.lastindexof("@")).concat(ext);
    // full path
    string filepath = path + file.separator + fname;

    system.out.println(fname + " and " + filepath);

    file f = new file(path);
    if (!f.exists()) {
        f.mkdir();
    }

    file convertedfile = new file(filepath);

    fileoutputstream fos = new fileoutputstream(convertedfile);
    system.out.println("-----started------");
    
    fos.write(bs);
    fos.close();
    system.out.println("-----closed------");
}
Copy after login

I'm trying to upload an image into a folder. When uploading an image segmented file to a folder using file.getinputstream, I get the following error

org.springframework.web.multipart.support.StandardServletMultipartResolver[0;39m: Failed to perform cleanup of multipart items
java.io.UncheckedIOException: Cannot delete D:\JS Projects\myapp\BackEnd\UserLoginSignUp\images\work\Tomcat-2\localhost\ROOT\upload_d31827cc_51e6_4901_b60e_6afdd0ee8a99_00000004.tmp
at org.apache.tomcat.util.http.fileupload.disk.DiskFileItem.delete(DiskFileItem.java:431)
at org.apache.catalina.core.ApplicationPart.delete(ApplicationPart.java:53)
at org.springframework.web.multipart.support.StandardServletMultipartResolver.cleanupMultipart(StandardServletMultipartResolver.java:134)
at org.springframework.web.servlet.DispatcherServlet.cleanupMultipart(DispatcherServlet.java:1251)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1108)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:965)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:555)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:623)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:209)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:153)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:51)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:178)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:153)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:178)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:153)
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:178)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:153)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:117)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:178)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:153)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:167)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:90)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:481)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:130)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:93)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:390)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:63)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:926)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1791)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:52)
at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191)
at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.base/java.lang.Thread.run(Thread.java:833)
Copy after login

What may be the causes of the above errors and exceptions? How do we solve the above problems?

Workaround

Consider using files.copy(), it will save you a lot of work.

public void saveFile(String directory, MultipartFile file) {
    if (file.isEmpty()) {
        return;
    }

    String fileName = file.getOriginalFilename();
    if (Objects.isNull(fileName) || fileName.isEmpty()) {
        fileName = UUID.randomUUID().toString();
    }
    try {
        Path path = Paths.get(directory);
        Files.copy(file.getInputStream(), path.resolve(fileName));
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}
Copy after login

The above is the detailed content of Unable to upload image in Spring Boot application. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)