Search code examples
javaspringhttp-status-code-404

Why my newly uploaded file cannot be displayed or opened


I wrote some code to upload files to the server. After I upload the file, I am redirected to the home page. I can’t open the file in the browser or preview it through JS, it displays a 404 error. All information in the database is initially displayed correctly(size, filename,etc). However, if I restart the project or relogin, the image will be displayed correctly and I can open it through the browser’s address bar (or with preview script).

Uploader controller

import com.example.restapifilemanager.model.UserModel;
import com.example.restapifilemanager.model.fileModel;
import com.example.restapifilemanager.repo.fileModelRepo;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.text.DecimalFormat;
import java.io.File;
import java.io.IOException;

@Controller
@SessionAttributes("user")
public class fileController {
    @Autowired
    private fileModelRepo fileModelRepo;

    @PostMapping("/upload")
    public String handleFileUpload(@RequestParam("file") MultipartFile file, Model model) throws IOException{
        UserModel user = (UserModel) model.getAttribute("user");
        if (!file.isEmpty())  {
            try {
                String fileCode = RandomStringUtils.randomAlphanumeric(10);
                String uploadDir = "D:\\restApiFileManager\\src\\main\\resources\\static\\files-upload";
                File uploadDirFile = new File(uploadDir);

                if (!uploadDirFile.exists()) {
                    uploadDirFile.mkdirs();
                }

                String fileName = file.getOriginalFilename();
                String filePath = uploadDir + File.separator +fileCode +fileName;

                file.transferTo(new File(filePath));
                

                Double sizeD = (double)file.getSize()/1024/1024;
                final DecimalFormat decfor = new DecimalFormat("0.00");
                String size = String.valueOf(decfor.format(sizeD)) + "MB";

                fileModel fileModel = new fileModel(size,fileName);
                fileModel.setUri(fileCode);
                if(user!=null)
                {
                    fileModel.setUser(user);
                }
                fileModelRepo.save(fileModel);

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return "redirect:/home";
    }
}


public interface fileModelRepo extends JpaRepository<fileModel, Long> {}


package com.example.restapifilemanager.model;


import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.JoinColumn;
import jakarta.persistence.ManyToOne;
import jakarta.persistence.Table;

@Entity
@Table(name = "Files")
public class fileModel
{
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;

    private String size, fileName,uri;

    @ManyToOne
    @JoinColumn(name = "user")
    private UserModel user;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getSize() {
        return size;
    }

    public void setSize(String size) {
        this.size = size;
    }

    public String getFileName() {
        return fileName;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }

    public String getUri() {
        return uri;
    }

    public void setUri(String uri) {
        this.uri = uri;
    }

    public UserModel getUser() {
        return user;
    }

    public void setUser(UserModel user) {
        this.user = user;
    }

    public fileModel(){}
    
    public fileModel(String size, String fileName) {
        this.size = size;
        this.fileName = fileName;
    }
}

the fileModelRepo just extends JpaRepository

Please help me to display my image correctly.


Solution

  • add spring.web.resources.static-locations[0]=file:src/main/resources/static/ spring.web.resources.static-locations[1]=classpath:/static/

    in application.properties