无法使用获取javascript发送大负载

b5lpy0ml  于 2021-09-23  发布在  Java
关注(0)|答案(2)|浏览(351)

我是javascript和nodejs领域的初学者。我试图用nodejs创建一个简单的文件上传项目。此外,我在nodejs中创建了路由,从网页中捕获图像,并使用fetch将其发送到nodejs路由。这是html文件:

  1. <div class="file-upload">
  2. <div class="image-upload-wrap">
  3. <input class="file-upload-input" type='file' onchange="readURL(this);" accept="image/*" />
  4. <div class="drag-text">
  5. <h3>Drag and drop a file or select add Image</h3>
  6. </div>
  7. </div>
  8. <div class="file-upload-content">
  9. <div class="file-upload-display">
  10. <img id="file-upload-image" class="file-upload-image" src="#" alt="your image" />
  11. <div class="image-title-wrap">
  12. <button type="button" onclick="removeUpload()" class="remove-image"><i class="fas fa-trash-alt"></i> Remove <span class="image-title">Uploaded Image</span></button>
  13. </div>
  14. </div>
  15. </div>
  16. </div>
  17. <br>
  18. <div class="file-upload-server d-flex justify-content-center">
  19. <button class="btn btn-expand-lg btn-primary" onclick="uploadFile()"><i class="fas fa-cloud-upload-alt"></i> Upload</button>
  20. </div>

这是我的javascript文件:

  1. async function uploadFile() {
  2. let img = document.getElementById('file-upload-image').src;
  3. console.log('Image String Length: ' + img.length);
  4. const payload = {
  5. method: 'POST',
  6. headers: {
  7. 'Content-Type': 'application/json'
  8. },
  9. body: JSON.stringify({
  10. file: img,
  11. })
  12. }
  13. console.log(`Payload: ${JSON.stringify(payload)}`);
  14. await fetch('http://localhost:3030/image/uploadimage', payload)
  15. .then(response => response.json())
  16. .then(data => {
  17. console.log('Success:', data);
  18. })
  19. .catch((error) => {
  20. console.error('Error:', error);
  21. });
  22. }

这里的图像是base64编码的字符串,我将其传递给我的nodejs路由。
单击“上载”按钮时,出现以下错误:

我用一个大小为5.72kb的图像测试了这段代码,它可以正常工作。但是当我尝试上传一个81.7kb大小的图像时,它失败了,出现了这个错误。
这是nodejs路由:

  1. router.use(imageupload({
  2. limits: { fileSize: 50 * 1024 * 1024 },
  3. }));
  4. router.use(express.urlencoded({limit: '50mb', extended: true}));
  5. router.use(express.json());
  6. const decodeBase64Image = (dataString) => {
  7. let matches = dataString.match(/^data:([A-Za-z-+\/]+);base64,(.+)$/),
  8. response = {};
  9. if (matches.length !== 3) {
  10. return new Error('Invalid input string');
  11. }
  12. response.type = matches[1];
  13. response.data = Buffer.from(matches[2], 'base64');
  14. return response;
  15. }
  16. router.post('/uploadimage', cors(corsOptions), async (req, res) => {
  17. let decodedImage = decodeBase64Image(req.body.file);
  18. let imageBuffer = decodedImage.data;
  19. let type = decodedImage.type;
  20. let extension = mime.getExtension(type);
  21. let NewImageName = Math.random().toString(36).substring(7);
  22. let fileName = 'image-' + NewImageName + '.' + extension;
  23. try {
  24. fs.writeFile(`${path.join(__dirname, '../')}/public/uploads/${fileName}`,
  25. imageBuffer, function(err) {
  26. if(err) throw err;
  27. console.log('The file was uploaded successfully');
  28. return res.status(200).json({status: 'success', message: 'File uploaded successfully'});
  29. });
  30. } catch(err) {
  31. console.log(err);
  32. return res.status(500).send(err);
  33. }
  34. });

任何关于这方面的帮助或指导都是非常好的。

vpfxa7rd

vpfxa7rd1#

您需要为您的应用程序设置上载限制 express.json() 中间件,因为您正在使用 'Content-Type': 'application/json' post请求中的标题。
试着替换 router.use(express.json()) 具有 router.use(express.json({ limit: '50mb'}) 文档

编辑

错误 Unexpected token < in JSON at position 0' 如果您尝试使用 response.json() 它的格式不是 json . 您可以在nodejs中以一行代码的形式将其复制为 JSON.parse('I am no json...') 如果你打电话 response.json() 在客户端上,它必须正确格式化 json 否则会导致错误。为此,请使用 res.json() 而不是 res.send() .
您还应确保始终回复客户,因此更改线路 if(err) throw err;

  1. if(err) {
  2. console.error(err)
  3. // always send back a status, 500 means server error..
  4. res.status(500).json('Internal server error')
  5. return
  6. }
dphi5xsq

dphi5xsq2#

我建议你用multer这里有个链接
后端代码示例:

  1. var multer = require('multer')
  2. var signature = multer.diskStorage({
  3. destination: function (req, file, cb) {
  4. cb(null, './public/')
  5. },
  6. filename: function (req, file, cb) {
  7. if (file.mimetype == 'image/jpeg' || file.mimetype === 'image/jpg' || file.mimetype === 'image/png' || file.mimetype === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') {
  8. cb(null, Date.now() + file.originalname)
  9. } else {
  10. cb({ error: 'Image type not supported' })
  11. }
  12. }
  13. })
  14. var uploadSignature = multer({ storage: signature })
  15. router.put('/updateWorkOrderForSign',uploadSignature.array('signature', 1), function (req, res) {
  16. try {
  17. if (req.body.signature) {
  18. var base64Data = req.body.signature.replace(/^data:image\/png;base64,/, "");
  19. let rString = Math.random().toString(36).substring(7);
  20. let date = Date.now();
  21. let imageName = '/' + date + rString + '.png';
  22. let imagePath = '/public' + imageName;
  23. require("fs").writeFile('./' + imagePath, base64Data, 'base64', function (err) {
  24. if (err) {
  25. log.error('SAVE IMAGE FAILED WITH ERROR: ', err);
  26. } else {
  27. log.info('Signature image saved successfully')
  28. }
  29. });
  30. } else {
  31. //nothing to do
  32. log.error("No signature image present")
  33. }
  34. } catch (err) {
  35. log.error('ERROR WHILE CONVERTING BASE64 TO IMAGE: ', err);
  36. }
  37. })

前端代码示例(我在react native中实现了此示例):

  1. async function uploadFile() {
  2. let imageObject = {
  3. uri: image.path,
  4. type: 'image/png',
  5. name: 'signatureImage'
  6. }
  7. var form = new FormData();
  8. form.append('signature', imageObject)
  9. form.append(‘taskId, taskId);
  10. await fetch(urlStr, {
  11. method: 'PUT',
  12. headers: {
  13. 'Authorization': bearerToken,
  14. Accept: 'application/json',
  15. 'Content-Type': 'multipart/form-data'},
  16. body: params,
  17. })
  18. .then(response => response.json())
  19. .then(responseData => {
  20. var result = JSON.stringify(responseData);
  21. return result;
  22. })
  23. .catch(error => {
  24. console.log('ERROR WHILE UPLOADING IMAGE: ',error)
  25. });
  26. }
展开查看全部

相关问题