Home > Java > body text

Unable to upload image in Spring Boot application

PHPz
Release: 2024-02-22 12:58:06
forward
925 people have browsed it

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!

source:stackoverflow.com
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!