Next.js 画像アップロードの例

2 min read読了の目安(約2500字

概要:

Next.js で、画像アップロード機能のメモとなります

  • multer で転送する例です

環境

  • node 14
  • next.js: 10.0.0

関連

https://dev.to/jtfinlay/file-upload-in-next-js-and-typescript-4gf8


参考のコード

https://github.com/kuc-arc-f/nextjs_3_9file
  • upload
    転送後に , fs.rename でファイル名変更する例です

/pages/api/file_upload.js

file_upload.js
import multer from 'multer';
import initMiddleware from '../../libs/init-middleware';
const fs = require('fs');

const upload = multer({
  storage: multer.diskStorage({
    destination: './public/uploads',
    filename: (req, file, cb) => cb(null, file.originalname),
  }),
});

const multerAny = initMiddleware(
  upload.any()
);

export const config = {
  api: {
      bodyParser: false,
  },
}
//
export default async function (req, res){
  try{
    await multerAny(req, res);
    if (!req.files?.length || req.files.length > 1) {
      res.statusCode = 400;
      res.end();
      return;
    }
//console.log("len=", req.files.length)
    const blob= req.files[0];
console.log("originalname=", blob.originalname)
    var originalname = blob.originalname
    var dir_base = "/home/naka/work/node/react/nextjs_3_9file/"
    var dir_public = dir_base + "public/uploads/"
    var new_name = "temp_" + originalname
    fs.rename(dir_public+ originalname , dir_public + new_name, (err) => {
      if (err) throw err;
    });    
//console.log(dir_base)
//console.log(blob)
    res.json({});
  } catch (err) {
      console.log(err);
      res.status(500).send(); 
  }   
};



  • 送信画面

INPUT type= file のchange イベントで起動、 xhrで送信

/pages/file.js

file_upload.js
export default class extends React.Component {
// console.log(data.blogs)
  static async getInitialProps(ctx) {
    var BASE_URL = LibConst.get_config().BASE_URL
    return {
      data: "",
      items: [],
      csrf:{}, BASE_URL: BASE_URL,
    }
  }
  constructor(props){
    super(props)
//console.log(props )
  }
  componentDidMount(){
    window.document.getElementById("file1").addEventListener("change", function() {
      console.log("#change");
      ImageTransfer.upload('file1');
    });    
  }
  clickHandler(){
  }
  render(){
    return (
    <Layout>
      <div className="body_main_wrap">
        <div className="container"><h1>File Upload test:</h1>
        <hr />
          file : <br />
          <input type="file" name="file1" id="file1" /><br /><br />
        </div>
      </div>
    </Layout>
    )
  }
}