我无法将图像和表单数据发送到 mysql。我的后端是 Java,使用邮递员时它工作正常。当我从前端发送它时,我无法这样做。我有用户名、标题、描述等以及图像的输入字段。请帮助我哪里错了。
问问题
209 次
2 回答
0
问题是,您正在尝试发送错误的文件名。您必须像这样附加文件:
var file = event.target.files[0];
const formData = new FormData();
formData.append("file", file);
formData.append("var1", val1); // Other fields
await fetch("url", {
method: "POST",
body: formData
}).then({
// code here
}).catch({
// code here
});
在服务器端,您将获取文件file
或您在将其附加到 formdata 时提供的任何名称。
于 2020-07-09T06:15:01.770 回答
0
请使用这个技巧
React:将您的媒体文件转换为 base64 字符串。
Java: 将 base64 转换为图像(img、pdf、xlxs 等...)
将图像转换为 Base64(REACT.JS):
function convertBase64(url, callback) {
var xhr = new XMLHttpRequest();
xhr.onload = function () {
var reader = new FileReader();
reader.onloadend = function () {
callback(reader.result);
}
reader.readAsDataURL(xhr.response);
};
xhr.open('GET', url);
xhr.responseType = 'blob';
xhr.send();
}
convertBase64("path-of-the-image/user_picture.png", function (dataUrl) {
//console.log('RESULT:', dataUrl);
});
将 Base64 转换为图像(JAVA):
// Needed Imports
import java.io.ByteArrayInputStream;
import sun.misc.BASE64Decoder;
def sourceData = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAPAAAADwCAYAAAA+VemSAAAgAEl...==';
// tokenize the data
def parts = sourceData.tokenize(",");
def imageString = parts[1];
// create a buffered image
BufferedImage image = null;
byte[] imageByte;
BASE64Decoder decoder = new BASE64Decoder();
imageByte = decoder.decodeBuffer(imageString);
ByteArrayInputStream bis = new ByteArrayInputStream(imageByte);
image = ImageIO.read(bis);
bis.close();
// write the image to a file
File outputfile = new File("image.png");
ImageIO.write(image, "png", outputfile);
于 2020-07-09T06:20:50.783 回答