如何获取上载的文件路径作为来自rest-api调用的响应

时间:2019-07-14 10:10:59

标签: reactjs

我有一个reactjs页面,该页面将文件上传到服务器。该服务器只是一个Spring-boot应用程序,该应用程序托管rest api以服务于上载。上传文件后,我想返回上传文件的绝对路径作为响应的一部分。我也能够实现这一点,但是当我用控制台记录日志时,响应正文仅显示ReadableStream。发送响应之前,我没有得到春季设置的文件的实际路径。

我尝试将响应实体对象设置为包含字符串格式的响应json的正文。

反应代码:

import React from 'react';
class UploadImage extends React.Component{
    constructor(props){
        super(props);
        this.state={
            uploadData:''
        }
        this.handleFileUpload=this.handleFileUpload.bind(this);
    }
    handleFileUpload=(event)=>{
        event.preventDefault();
        //alert('uploaded file')
        //console.log(this.uploadedFile.files[0]);
        const data = new FormData();
        data.append('uploadedFile',this.uploadedFile.files[0]);

        fetch('http://localhost:8080/laptops/upload',{
            method:'POST',
            body:data
        }).then((response) => {
            console.log(response);
            console.log(response.json);
          });
    }
    render(){
        return (
            <div>
                <form onSubmit={this.handleFileUpload}>
                    <input type='file' ref={(ref)=>{this.uploadedFile=ref}}/>
                    <input type='submit' value='upload'/>
                </form>
            </div>
        );
    }
}
export default UploadImage;

引导代码:(仅查看发布映射功能)

package react.demo.app;

import oracle.jdbc.proxy.annotation.Post;
import org.apache.commons.io.FilenameUtils;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.persistence.*;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;

@Entity
class Laptop{
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long id;
    private String name;
    private String brand;
    private double price;
    private String image;
    public Laptop(){

    }
    public Laptop(String name,String brand,double price,String image){
        this.name=name;
        this.brand=brand;
        this.price=price;
        this.image=image;
    }
    public long getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getBrand() {
        return brand;
    }

    public void setBrand(String brand) {
        this.brand = brand;
    }

    public double getPrice() {
        return price;
    }

    public void setPrice(double price) {
        this.price = price;
    }

    public String getImage() {
        return image;
    }

    public void setImage(String image) {
        this.image = image;
    }
}
@Repository
interface LaptopRepository extends JpaRepository<Laptop,Long>{}

@Service
class LaptopService{
@Autowired
LaptopRepository laptopRepository;
public void addLaptop(Laptop laptop){
    laptopRepository.save(laptop);
}
public Laptop getLaptopById(long id){return laptopRepository.getOne(id); }
public List<Laptop> getAllLaptops(){
    return laptopRepository.findAll();
}
}
@RestController
@RequestMapping("/laptops")
class LaptopApi{
    @Autowired LaptopService laptopService;
    private String uploadDir = "C:\\Users\\rajen\\Development\\upload_images\\";
    @CrossOrigin(origins = "http://localhost:3000")
    @GetMapping(value="/",produces="application/json")
    public List<Laptop> getAllLaptops(){
        return laptopService.getAllLaptops();
    }
    @CrossOrigin(origins = "http://localhost:3000")
    @PostMapping(value = "/upload")
    public ResponseEntity upload(@RequestParam("uploadedFile") MultipartFile uploadedFile) throws IOException {
        System.out.println("invoked upload");
        File f = new File(uploadDir+uploadedFile.getOriginalFilename());
        uploadedFile.transferTo(f);
        System.out.println("return uploaded file:"+f.toURI());
        HttpHeaders responseHeaders = new HttpHeaders();
        return ResponseEntity.ok().headers(responseHeaders).body("{uploadedfile:"+f.getAbsolutePath()+"}");
    }
    @GetMapping(value="/getLaptopById",produces="application/json")
    public Laptop getLaptopById(@RequestParam long id){
        System.out.println("laptop by id:"+id);
        return laptopService.getLaptopById(id);
    }
    @PostMapping(value="/addLaptop")
    public void addLaptop(@RequestBody Laptop laptop){
        laptopService.addLaptop(laptop);
    }

}
@SpringBootApplication
public class AppApplication implements CommandLineRunner {
    @Autowired LaptopService laptopService;
    public static void main(String[] args){
        SpringApplication.run(AppApplication.class,args);
    }
    @Override
    public void run(String... args) throws Exception {
        Laptop laptop = new Laptop("Dell Inspiron","Dell",new Double(25990),"https://i.pinimg.com/564x/4a/bb/86/4abb8659d4d951a6fefefe401a02aeb7.jpg");
        laptopService.addLaptop(laptop);
        System.out.println("Laptop Added");
    }

}

我希望将文件路径视为响应主体的一部分,但仅将Readablestream作为主体。

Refer to console log here

1 个答案:

答案 0 :(得分:0)

假设您正在接收json有效负载,则需要在promise上调用.json()方法,以提取主体数据,然后返回该值(与仅访问.json的尝试相反)响应)。另外,如果主体数据只是文本-可能会为其赋予您要返回的值,则可能需要调用.text()方法。

      fetch('http://localhost:8080/laptops/upload', {
            method:'POST',
            body:data
          }).then((response) => {
             return response.json();
          }).then(finalRes => console.log(finalRes))
         .catch(e)
    }