【问题标题】:ReactJS component to upload a file to a Spring MVC/Data-REST serverReactJS 组件将文件上传到 Spring MVC/Data-REST 服务器
【发布时间】:2016-06-06 20:17:17
【问题描述】:

我一直在寻找 ReactJS component 以允许您从 browser 上传文件并将其保存到运行 ReactJS 的服务器上。

我找到了各种components 用于drag and drop 等,superagent 用于可能将文件保存到服务器,但我认为有人可能为所有这些创建了component

后端是一个使用 Spring Boot、Spring Data JPA 和 Spring Data REST 的 Java 应用程序。

有谁知道有关设置将文件保存到服务器的基本方法的教程或教程?

解决方案

最后,我使用了下面的部分解决方案与 dropzone 和 superagent,然后使用了 Spring 指南 (https://spring.io/guides/gs/uploading-files/)

上传器组件

'use strict';

const React = require('react');
const ReactDOM = require('react-dom');

const log = require('./log'); // logger to enable debug alerts

// import the components
const Dropzone = require('react-dropzone');
const request = require('superagent');

//'application/java-archive'
class Uploader extends React.Component {
  constructor(props) {
    super(props);
    this.dropHandler = this.dropHandler.bind(this);
  }

  dropHandler(file) {
    var jsonFile = new FormData();
    jsonFile.append('file', file[0]);
    jsonFile.append('name', file[0].name);

    request.post('/upload')
    .send(jsonFile)
    .end(function(err, resp) {
      if (err) {
        console.error(err);
      }
      return resp;
    });
  }


  render() {
    return (
      <Dropzone disableClick={false} multiple={false} accept={'application/java-archive'} onDrop={this.dropHandler}>
        < div > Drop a Appium Jar, or click to add. < /div >
      </Dropzone>
    );
  }
}

module.exports = Uploader

文件上传控制器

@Controller
public class FileUploadController {

    @RequestMapping(value="/upload", method=RequestMethod.GET)
    public @ResponseBody String provideUploadInfo() {
        return "You can upload a file by posting to this same URL.";
    }

    @RequestMapping(value="/upload", method=RequestMethod.POST)
    public @ResponseBody ResponseEntity<String>  handleFileUpload(@RequestParam("name") String name,
            @RequestParam("file") MultipartFile file) throws Exception{
        if (name.contains("/")) {
            return ResponseEntity.status(HttpStatus.UNPROCESSABLE_ENTITY).body("Folder separators not allowed.");
        } else if (name.contains("/")) {
            return ResponseEntity.status(HttpStatus.UNPROCESSABLE_ENTITY).body("Relative pathnames not allowed.");
        } else if (!name.endsWith(".jar")) {
            return ResponseEntity.status(HttpStatus.UNPROCESSABLE_ENTITY).body("File type not allowed.  Must be a Jar file type ending in '.jar'.");
        }

        if (!file.isEmpty()) {
            try {
                byte[] bytes = file.getBytes();
                BufferedOutputStream stream =
                        new BufferedOutputStream(new FileOutputStream(new File(name)));
                stream.write(bytes);
                stream.close();
                return ResponseEntity.ok("File " + name + " uploaded.");
            } catch (Exception e) {
                return ResponseEntity.status(HttpStatus.UNPROCESSABLE_ENTITY).body(e.getMessage());
            }
        } else {
            return ResponseEntity.status(HttpStatus.UNPROCESSABLE_ENTITY).body("You failed to upload " + name + " because the file was empty.");
        }
    }
}

【问题讨论】:

  • 这真的取决于您计划将文件存储在哪里/您的后端是什么样的。我将首先找到一种可访问的 ajax 方法来保存文件。从那里开始,构建一个响应组件来执行 ajax 调用是相当简单的,而且您可能不需要外部组件的帮助来实现。

标签: javascript ajax html browser reactjs


【解决方案1】:

您可能希望通过您的服务器来执行此操作。你使用什么样的后端?如果您使用的是 Node.js,则有一个名为 Multer 的 npm 模块将文件保存到您的服务器。我在关于react dropzones 的博文中谈到了它。如果没有关于您的后端的更多信息,很难准确地说出您需要做什么。

【讨论】:

    猜你喜欢
    • 2016-05-26
    • 2020-06-05
    • 2012-12-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-11
    相关资源
    最近更新 更多