前端代码:
react:
- render() {
- let url = this.state.file;
- return <div className="input-group">
- <input id="file" onChange={(e) => this.handleChange(e)} type="file" className="form-control" placeholder="请选择文件" />
- <span className="input-group-btn">
- <button onClick={() => this.addResource()} className="btn btn-primary" type="button">上传文件</button>
- </span>
- </div>
js:
- handleChange(e: any) {
- e.preventDefault();
- let target = e.target;
- let files = target.files;
- this.setState({
- file: files[0]
- })
- }
- addResource() {
- if (!this.state.file) {
- alert('请选择文件');
- return;
- }
- let formData = new FormData();
- formData.append('fileData', this.state.file)
- fetch('/XXXXX ', {
- method: 'POST',
- credentials: "include",
- body: formData,
- headers: {
- "accept": "application/json"
- },
- }).then((res) => {
- console.log(res);
- return res.json();
- }).then((res) => {
- })
- }
- if (!this.state.file) {
node:
- export const add: Middleware = async (ctx, next) => {
- let req = ctx.req;
- let body = "";
- let boundary: any = ctx.headers['content-type'].split(';')[1].replace('boundary=', '');
- req.setEncoding("binary");
- await new Promise((ok, fail) => {
- req.on('data', (chunk) => {
- body += chunk;
- })
- req.on('end', () => {
- let file = body.split(('--' + boundary).replace(" ", "")),
- i = 1;
- for (let i = 1, c = file.length - 1; i < c; i++) {
- let something = querystring.parse(file[i], "\r\n", ": ");
- file[i].match(/Content-Type: (.*)\r\n/)
- if (something['Content-Type']) {
- //把文件名改为时间戳
- let type = something['Content-Disposition'].split('filename=')[1].replace(/"/g, '').trim().split('.')
- let fileName = String(new Date().getTime()) + '.' + type[type.length - 1]
- let contentType = something['Content-Type']
- let upperBoundary = body.indexOf(contentType) + contentType.length//获取文件二进制数据开始位置,即contentType的结尾
- let shorterData = body.substring(upperBoundary) // 替换开始位置的空格和结尾的空格
- let binaryDataAlmost = shorterData.trim();
- let binaryData = binaryDataAlmost.substring(0, binaryDataAlmost.indexOf(('--' + boundary + '--').replace(" ", ""))) // 去除数据末尾的额外数据,即: "--"+ boundary + "--"
- let homeDir = path.resolve(__dirname, '../../..', 'resource')
- if (mkdirsSync(homeDir)) {
- try {
- fs.writeFileSync(path.join(homeDir, fileName), binaryData, 'binary');
- console.log('上传完成');
- ctx.body = {
- msg: '上传完成',
- code: 1
- }
- ok();
- } catch (e) {
- console.log(e);
- throw Boom.badImplementation();
- }
- } else {
- let Err = Boom.badImplementation();
- ctx.throw(Err);
- }
- } else {
- let Err = Boom.badData("上传的不是文件");
- ctx.throw(Err);
- }
- }
- })
- req.on('data', (chunk) => {
- })
- }