Image upload is not working in Spring Boot.

huangapple go评论54阅读模式
英文:

Image upload is not working in Spring Boot

问题

I am building a web app using Spring Boot and I need the user to upload an image. I am stuck at the backend of this problem. I have written the following code in the controller. The app is running fine, and when I upload the file through postman, it returns the image URL with status 200 (ok), but the file does not get added to the folder. Please suggest what is wrong here. Please keep it as detailed as possible.

Here's my code to upload an image that I have written in the controller:

@PostMapping("/image/upload")
public ResponseEntity<String> uploadImage(@RequestParam("file") MultipartFile file) {
    String message = "Image is successfully uploaded";
    try {
        String uploadPath = staticDir + "testfile_" + System.currentTimeMillis() + "_" + file.getOriginalFilename();
        file.transferTo(new File(uploadPath));
        message = "Image URL: " + uploadPath;
        return ResponseEntity.status(HttpStatus.OK).body(message);
    } catch (Exception e) {
        LOGGER.error("Exception occurred: {}", e);
        message = "Could not upload the file: " + file.getOriginalFilename() + "!";
        return ResponseEntity.status(HttpStatus.EXPECTATION_FAILED).body(message);
    }
}

I have annotated staticDir with @Value to get its value from application.properties:

@Value("${static.dir.path}")
private String staticDir;

In application.properties:

static.dir.path=C:\Users\rjuna\IdeaProjects\visitor-management-system\images

Then I have a configuration for the application to access the image through port 8080:

@Configuration
@EnableWebMvc
public class MvcConfig implements WebMvcConfigurer {
    @Value("${static.dir.path}")
    private String staticDir;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry
            .addResourceHandler("/vms/**")
            .addResourceLocations("C:/Users/rjuna/IdeaProjects/visitor-management-system/images/");
    }
}

"/vms/**" is a pattern. The app will find any file or URL with this pattern in the location given just below the pattern. Now I am searching with this URL:

localhost:8080/vms/testfile_1681807188450_My_Photo.jpg

But I am getting a 404 - Not found error, both in the browser and Postman. The API returns the image URL, which is the file location on my computer. However, I want to access the image through the application, i.e., through localhost:8080, and that is not working. Please suggest a solution for this.

英文:

I am building a web app using Spring Boot and I need the user to upload image. I am stuck at the backend of this problem. I have written the following code in controller. The app is running fine and when I upload the file through postman, it returns the image URL with status 200(ok) but the file does not get added to the folder.
Please suggest what is wrong here. Please keep it as detailed as possible.

Here's my code to upload image that I have written in the controller

@PostMapping(&quot;/image/upload&quot;)
    public ResponseEntity&lt;String&gt; uploadImage(@RequestParam(&quot;file&quot;) MultipartFile file) {
        String message = &quot;Image is successfully uploaded&quot;;
        try {
            String uploadPath = staticDir+&quot;testfile_&quot;+System.currentTimeMillis()+&quot;_&quot;+file.getOriginalFilename();
            file.transferTo(new File(uploadPath));
            message = &quot;Image URL : &quot; + uploadPath;
            return ResponseEntity.status(HttpStatus.OK).body(message);
        } catch (Exception e) {
            LOGGER.error(&quot;Exception occurred: {}&quot;,e);
            message = &quot;Could not upload the file: &quot; + file.getOriginalFilename() + &quot;!&quot;;
            return ResponseEntity.status(HttpStatus.EXPECTATION_FAILED).body(message);
        }

    }

I have annotated staticDir with @Value to get it's value from application.properties

@Value(&quot;${static.dir.path}&quot;)
    private String staticDir;

> application.properties
static.dir.path=C:\Users\rjuna\IdeaProjects\visitor-management-system\images

Then I have a configuration for application to access the image through port 8080.

@Configuration
@EnableWebMvc
public class MvcConfig  implements WebMvcConfigurer {
@Value(&quot;${static.dir.path}&quot;)
private String staticDir;

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry
          .addResourceHandler(&quot;/vms/**&quot;)
          .addResourceLocations(&quot;C:/Users/rjuna/IdeaProjects/visitor-management-system/images/&quot;);
}
}

"/vms/**" is a pattern. App will find any file of URL with this pattern in the location given just below the pattern. Now I am searching with this URL

localhost:8080/vms/testfile_1681807188450_My_Photo.jpg

But I am getting 404- Not found, both in the browser and postman. The API returns the image URL which is the file location in my computer. Though I want to access the image through the application i.e. through localhost:8080 and that is not working. Please suggest a solution for this.

答案1

得分: 0

文件保存到错误位置,原因是缺少路径分隔符 / 或 \。

要么

String uploadPath = staticDir + "/testfile_" + System.currentTimeMillis() + "_" + file.getOriginalFilename();

要么

static.dir.path=C:\\Users\\rjuna\\IdeaProjects\\visitor-management-system\\images\\
英文:

The file is being written to the incorrect location because of a missing path separator / or \.

Either

        String uploadPath = staticDir+&quot;/testfile_&quot;+System.currentTimeMillis()+&quot;_&quot;+file.getOriginalFilename();

Or

static.dir.path=C:\Users\rjuna\IdeaProjects\visitor-management-system\images\

huangapple
  • 本文由 发表于 2023年4月17日 18:36:17
  • 转载请务必保留本文链接:https://go.coder-hub.com/76034234.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定