Angular File Upload

后端 未结 12 2157
名媛妹妹
名媛妹妹 2020-11-22 10:04

I\'m a beginner with Angular, I want to know how to create Angular 5 File upload part, I\'m trying to find any tutorial or doc, but I don\'t see anything a

12条回答
  •  南方客
    南方客 (楼主)
    2020-11-22 10:41

    1. HTML
    
        

    1. ts File
    public formData = new FormData();
    ReqJson: any = {};
    
    uploadFiles( file ) {
            console.log( 'file', file )
            for ( let i = 0; i < file.length; i++ ) {
                this.formData.append( "file", file[i], file[i]['name'] );
            }
        }
    
    RequestUpload() {
            this.ReqJson["patientId"] = "12"
            this.ReqJson["requesterName"] = "test1"
            this.ReqJson["requestDate"] = "1/1/2019"
            this.ReqJson["location"] = "INDIA"
            this.formData.append( 'Info', JSON.stringify( this.ReqJson ) )
                this.http.post( '/Request', this.formData )
                    .subscribe(( ) => {                 
                    });     
        }
    
    1. Backend Spring(java file)
    
    import java.io.IOException;
    import java.nio.file.Files;
    import java.nio.file.Path;
    import java.nio.file.Paths;
    
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.PostMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.ResponseBody;
    import org.springframework.web.multipart.MultipartFile;
    
    @Controller
    public class Request {
        private static String UPLOADED_FOLDER = "c://temp//";
    
        @PostMapping("/Request")
        @ResponseBody
        public String uploadFile(@RequestParam("file") MultipartFile file, @RequestParam("Info") String Info) {
            System.out.println("Json is" + Info);
            if (file.isEmpty()) {
                return "No file attached";
            }
            try {
                // Get the file and save it somewhere
                byte[] bytes = file.getBytes();
                Path path = Paths.get(UPLOADED_FOLDER + file.getOriginalFilename());
                Files.write(path, bytes);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return "Succuss";
        }
    }
    

    We have to create a folder "temp" in C drive, then this code will print the Json in console and save the uploaded file in the created folder

提交回复
热议问题