简体   繁体   English

我无法使用Java Spring Boot和Angular 7在远程服务器(Apache2)上上传文件。它在localhost上运行良好

[英]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). 我无法在远程服务器(apache2)上传文件(图像)。 I use java spring boot for back and Angular 7 for front). 我使用java spring boot for back和Angular 7 for front)。 On localhost:4200 it works well. 在localhost:4200它运作良好。 On a remote server I got from the chrome browser console : 在我从chrome浏览器控制台获得的远程服务器上:

POST http://www.xxx.tech:8081/images/upload 400 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"}" 错误:“{”timestamp“:”2019-05-10T09:39:38.162 + 0000“,”status“:400,”错误“:”错误请求“,”消息“:”找不到文件“,”路径“ : “/图片/上传”}”
headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, lazyInit: ƒ} headers:HttpHeaders {normalizedNames:Map(0),lazyUpdate:null,lazyInit:ƒ}
message: "Http failure response for http://www.xxx.tech:8081/images/upload : 400 OK" 消息:“ http://www.xxx.tech:8081/images/upload:400 OK的Http失败响应”
name: "HttpErrorResponse" 名称:“HttpErrorResponse”
ok: false 好的:假的
status: 400 状态:400
statusText: "OK" statusText:“确定”
url: " http://www.xxx.tech:8081/images/upload " 网址:“ http://www.xxx.tech:8081/images/upload

The directory folder already exist on the VPS server. 目录文件夹已存在于VPS服务器上。 How to make it work? 如何使它工作? In my controller.java I tried to replace 在我的controller.java中,我试图替换

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 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 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 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 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: 您可能希望添加显式目录创建,因为您的bean初始化方法类似于:

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 : @AlexGera你让我明白了问题所在:

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. 它没有解决问题,但它在后备文件夹中创建了一个文件夹:image / upload。 And, the rights of this folder was not root root like it is in all folders in filezilla server directory. 并且,此文件夹的权限不是root root,就像它位于filezilla服务器目录中的所有文件夹中一样。 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 所以,我更改了文件夹资产和文件夹img的权限(也许只有img,最后一个文件夹,应该可以工作,我不知道),因为我的路径是

/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 它奏效了

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 上传文件,angular spring开机 - upload files, angular spring boot Spring Boot Standalone在本地运行良好,但无法在远程服务器上访问 - Spring boot standalone runs well on local but cannot be accessed on remote server 无法在Java Spring Boot中将文件上传到tomcat托管服务器,始终在fedora中显示对给定文件上传路径的访问被拒绝 - Can't upload file in java spring boot to the tomcat hosting server, always show access denined for the given file upload path in fedora 如何使用 Java (Spring Boot) 将视频上传到 JWPlayer - How can I upload videos to JWPlayer with Java (Spring Boot) 我无法在NetBeans和Apache服务器中使用Java连接到远程数据库 - I can't connect to a remote db using java in netbeans and apache server Spring Boot 无法访问本地主机 Mongodb - Spring Boot can't reach localhost Mongodb 向 spring 发送请求时找不到 404 从 Angular 中运行的 api - 404 not found when sending requests to spring boot api from Angular running in Apache2 Kafka Java使用者仅适用于localhost,而远程服务器则失败 - Kafka Java consumer works only for localhost and fails for remote server Spring Boot App可在本地Tomcat上运行,但不能在远程服务器上运行 - Spring Boot App works on local Tomcat but not on remote server 如何在 spring 引导中为嵌入式 tomcat 服务器在 apache2 中配置反向代理? - How to configure reverse proxy in apache2 for embedded tomcat server in spring boot?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM