NodeJS 多个功能或需求的sveltekit操作

9vw9lbht  于 2023-03-29  发布在  Node.js
关注(0)|答案(1)|浏览(154)

我需要通过sveltekit动作上传图像,我在后端node.js和代码中使用了三个函数来完成。

import multer from 'multer';
import sharp from 'sharp';

const multerStorage = multer.memoryStorage();

const multerFilter = (req, file, cb) => {
  if (file.mimetype.startsWith('image')) {
    cb(null, true);
  }
  
  else {
    cb('Please upload only images !', false);
  }
};


const upload = multer({
    storage: multerStorage,
    fileFilter: multerFilter,
  });

  const uploadFiles = upload.array('images', 10);

  exports.uploadImages = (req, res, next) => {
    uploadFiles(req, res, (err) => {
      if (err instanceof multer.MulterError) {
        if (err.code === 'LIMIT_UNEXPECTED_FILE') {
          return res.send('Too many files to upload !');
        }
      } else if (err) {
        return res.send(err);
      }
  
      next();
    });
  };

  exports.resizeImages = async (req, res, next) => {
    if (!req.files) return next();
  
  req.body.images = [];
    await Promise.all(
      req.files.map(async (files,i) => {
        
   
        const newFilename = `tour-${files.originalname}-${Date.now()}-${i + 1}.jpeg`;
  
        await sharp(files.buffer) 
          .resize(640, 320)
          .toFormat('jpeg')
          .jpeg({ quality: 90 })
          .toFile(`upload/${newFilename}`);
         
        req.body.images.push(newFilename);
    // console.log(req.body.images);
  
   
    
  
  
   
  
  
      })
    );
  
    next();
  };
  
 
  
  exports.getResultImages = async (req, res,next) => {
    if (req.body.images.length <= 0) {
      
      return res.send(`You must select at least 1 image !`);
      
  
    }
   
    const images = req.body.images.map((image) => '' + image + '');
   // res.status(200).json(req.body.images)
   req.body.images = images;
    res.locals.images = images;
    console.log();
    next();

    
  
    
  };

那么,我如何使用sveltekit操作来处理请求,这是正确方法吗?或者我只需要从后端发出请求,对于multer和sharp,我的意思是处理sveltekit,有没有其他选择

gr8qqesn

gr8qqesn1#

这就是我发现的上传多个文件与svetekit它可能会帮助任何人.

+Page.server.js

import  sharp from 'sharp';

export const actions = {
    add: async ({ request }) => {
    const data = await request.formData()
    let file = data.getAll('file')
    console.log(file);
    const names = file.map(user => user.name);
    console.log(names);
    if (!file) return next();
  

    await Promise.all(
      file.map(async (file,i) => {
  
     let filename   = `tour-${"file.originalname"}-${Date.now()}-${i + 1}.jpeg`;

        if (file) {
            

          
          let ab = await file.arrayBuffer()
          console.log(Array.from(ab));
  

          await sharp(ab)
          .resize(500, 500)
          .toFormat('jpeg')
          .jpeg({ quality: 90 })
          .toFile(`static/img2/${filename}`);
          return { success: true }     
        }
    })
    
    );}
  };

+页面.苗条

<script>

    export let form
    export let data

</script>
<!-- svelte-ignore missing-declaration -->
<form 
    action="?/add"
    method="post"
    enctype="multipart/form-data" 
    
  >
<input
      multiple
      type="file"
      name="file"
      id="file"
      accept="image/*" class="file-input file-input-bordered file-input-error w-full max-w-xs"
    />
    <button>upload</button>
</form>

相关问题