简体   繁体   中英

I can't upload files on remote server (Apache2) with Java Spring Boot and Angular 7. It works well on localhost

I can't upload files (images) on remote server(apache2). I use java spring boot for back and Angular 7 for front). On localhost:4200 it works well. On a remote server I got from the chrome browser console :

POST http://www.xxx.tech:8081/images/upload 400

error: "{"timestamp":"2019-05-10T09:39:38.162+0000","status":400,"error":"Bad Request","message":"No file found","path":"/images/upload"}"
headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ}
message: "Http failure response for http://www.xxx.tech:8081/images/upload : 400 OK"
name: "HttpErrorResponse"
ok: false
status: 400
statusText: "OK"
url: " http://www.xxx.tech:8081/images/upload "

The directory folder already exist on the VPS server. How to make it work? In my controller.java I tried to replace

File tmp = new File("../front/assets/img/").getCanonicalFile();

with

File tmp = new File("./front/assets/img/").getCanonicalFile();

and with

File tmp = new File("/home/alexandra/www/front/assets/img/").getCanonicalFile();

But it still show the same error message

JAVA : ImageController.java

@PostMapping(value="images/upload")
    public String uploadImage( @RequestParam("file") MultipartFile transferedFile) throws Exception{
        try {
            //FOR LOCALHOST (works)
            //File tmp = new File("../FRONT- 
            //Alexandra/src/assets/img/").getCanonicalFile();

            //FOR REMOTE SERVER (don't work)
            File tmp = new File("../front/assets/img/").getCanonicalFile();

            String destination = tmp.getPath() + "/" + transferedFile.getOriginalFilename();

            File data = new File(destination);
            transferedFile.transferTo(data);
            Image image = new Image(transferedFile.getOriginalFilename(), destination);
            imageRepository.save(image);
            return destination;

            }catch( Exception param_exception) { 
                throw new ResponseStatusException(
                    HttpStatus.BAD_REQUEST,
                    "No file found");
            }
    }

Angular : mycomponent.component.ts

public apiUrl: string = environment.ApiUrl;
...

public uploadImaeg(): void {

      this.imgesUploaded.map(image => {

         if (image != null && image != undefined) {
            this.imagesService.addImage(image).subscribe();
         }  
      })     
   }

images.service.ts

public addImage(param_file: File): Observable<Object> {
        const headers: HttpHeaders = new HttpHeaders();
        const data: FormData = new FormData();

        data.append("file", param_file, param_file.name);
        headers.append("Content-Type", "multipart/form-data");
        const Obs: Observable<boolean> = this.serviceHttp.post(
            this.apiUrl + "images/upload", data, { headers: headers}
        ).pipe(
            map(
                (param_response: boolean) => {
                    return param_response;
                }
            )
        );
        return Obs;
    }

environment.prod.ts

export const environment = {
  production: true, 
  ApiUrl: 'http://'+document.location.hostname +':8081/'
};

I don't see you actually create a storage directory. You might be want to add explicit directory creation due your bean initialization method something like:

private final Path rootLocation = Paths.get("upload");
@PostConstruct
public void init() {
  try {
    Files.createDirectories(rootLocation);
  }
  catch (IOException e) {
     throw new StorageException("Could not initialize storage", e);
  }

}

@AlexGera you made me understand what the problem was :

I tryed your code like this :

private final Path rootLocation = Paths.get("images/upload");
    @PostConstruct
    public void init() {
      try {
        Files.createDirectories(rootLocation);
      }
      catch (IOException e) {
         throw new RuntimeException("Could not initialize storage", e);
      }
    }

    @PostMapping(value="images/upload")
    public String uploadImage( @RequestParam("file") MultipartFile transferedFile) throws Exception{
        try {

            File tmp = new File("/home/alexandra/www/front/assets/img/").getCanonicalFile();

            String destination = tmp.getPath() + "/" + transferedFile.getOriginalFilename();

            File data = new File(destination);
            transferedFile.transferTo(data);
            Image image = new Image(transferedFile.getOriginalFilename(), destination);
            imageRepository.save(image);
            return destination;

            }catch( Exception param_exception) { 
                throw new ResponseStatusException(
                    HttpStatus.BAD_REQUEST,
                    "No file found");
            }
    }

it didn't resolve the problem but it created a folder in the back folder : image/upload. And, the rights of this folder was not root root like it is in all folders in filezilla server directory. It was alexandra alexandra

So, I changed the rights of the folder assets and the folder img (maybe only img, last folder, should work, I don't know) because my path is

/home/alexandra/www/front/assets/img/

I did that :

cd /home/alexandra/www/front
sudo chown alexandra:alexandra assets
cd assets
sudo chown alexandra:alexandra img
sudo service myserver stop
sudo service myserver start
sudo systemctl restart apache2

And it worked

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM