简体   繁体   English

使用AJAX将图像上传到数据库不会作为blob上传

[英]Uploading image to database using AJAX is not uploading as blob

I have a webpage that is supposed to upload an image to the database with a name to describe the image. 我有一个网页,应该将图像上传到数据库,并带有描述图像的名称。 Think uploading a logo and the name of the companies logo. 考虑上传徽标和公司徽标的名称。

When I select the image file and submit it uploads to the database and I can return that information to the webpage in a list. 当我选择图像文件并将其上传到数据库时,我可以将该信息返回到列表中的网页。 However, it is not encoded in the manner that I was expecting. 但是,它没有以我期望的方式编码。 I would like the image file to be uploaded as a blob so that I may convert the blob to Base64 and pass it to my web application. 我希望将图像文件作为blob上传,以便我可以将blob转换为Base64并将其传递给我的Web应用程序。

This is what the blob code looks like if I manually upload the images using MySQLs gui. 如果我使用MySQLs手动上传图像,这就是blob代码的样子。 "iVBORw0KGgoAAAANSUhEUgAACWAAAAnHCAYAAAAIV..." which I'm able to convert to Base64 later. “iVBORw0KGgoAAAANSUhEUgAACWAAAAnHCAYAAAAIV ...”我稍后可以转换为Base64。

When I use my ajax web page to upload an image however, I receive "QzpcZmFrZXBhdGhcU3ByaW5nLnBuZw==". 当我使用我的ajax网页上传图像时,我会收到“QzpcZmFrZXBhdGhcU3ByaW5nLnBuZw ==”。

My question is, how can I have ajax upload it as a blob instead so that my Java application can properly call the blob and convert it to Base64? 我的问题是,如何让ajax将其作为blob上传,以便我的Java应用程序可以正确调用blob并将其转换为Base64?

ajax.js ajax.js

$(function (){

var $skills = $('#skills');
var $logo = $('#logo');
var $techName = $('#techName');

$.ajax({
    type: 'GET',
    url: '/api/technologyList',
    success: function(skills) {
        $.each(skills, function(i, skill) {
            $('#skills-list').append('<tr><td> ' + skill.logo + '</td>' + '<td>' + skill.techName + '</td></tr>')
        })

    }
})

$('#addSkill').on('click', function () {
    var skill = {
        techName: $techName.val(),
        logo: $logo.val()
    }
    $.ajax({
        type: 'POST',
        url:'/api/technologyList',
        data: skill,
        contentType: "multipart/form-data",
        processData: false,
        success: function (newSkill) {
            $('#skills-list').append('<tr><td> '+ newSkill.logo+ '</td>' +
                '<td> '+ newSkill.techName + '</td></tr>')
            console.log(skill)
        }
    })
})

})

addSkill.html addSkill.html

<table id="skills-list">
  <tr>
    <th>Logo</th>
    <th>Technology</th>
  </tr>
</table>

<form id="skillForm">
    <input type="text" id="techName"/> <br>
    <input type="file" enctype="multipart/form-data" id="logo"/>
    <button id="addSkill">Add!</button>
</form>

HomeController HomeController的

@GetMapping(value = "/technology")
public String technologyList(Model theModel) throws IOException {

    try {
        List<Skills> userSkillsList = skillsService.findSkillList("wmangram");

        List<byte[]> logo = skillsService.findLogos();
        List<String> base64List = new ArrayList<>();

        boolean isBase64 = false;

        for (int i = 0; i < logo.size(); i++) {
            if (Base64.isBase64(logo.get(i))) {
                String base64Encoded = new String((logo.get(i)), "UTF-8");
                base64List.add(base64Encoded);
            }
            else {
                byte[] encodeBase64 = Base64.encodeBase64(logo.get(i));
                String base64Encoded = new String(encodeBase64, "UTF-8");
                base64List.add(base64Encoded);
            }
        }

        theModel.addAttribute("userSkills", userSkillsList);
        theModel.addAttribute("userImages", base64List);

        return "technology";
    }
    catch (NullPointerException nexc) {
        return "nullexception";
    }
}

You have to use a FormData object to upload multipart/form-data 1 via ajax. 您必须使用FormData对象通过ajax上载multipart / form-data 1

$('#addSkill').on('click', function () {
    var skill = new FormData();
    skill.append("techName", $techName.val());
    skill.append("logo", $logo.prop("files")[0]);

    $.ajax({
        type: 'POST',
        url:'/api/technologyList',
        data: skill,
        contentType: false, //don't set this, it will be set automatically and properly 
        processData: false,
        success: function (newSkill) {
            $('#skills-list').append('<tr><td> '+ newSkill.logo+ '</td>' +
                '<td> '+ newSkill.techName + '</td></tr>')
            console.log(skill)
        }
    })
})

Looking at the java code it doesn't look like it can handle a file upload, so this answer is only for the client side code. 查看java代码看起来它不能处理文件上传,因此这个答案仅适用于客户端代码。

  1. This isn't strictly true but you wouldn't want to have to do it any other way. 这不是严格意义上的,但您不希望以任何其他方式执行此操作。

The problem was that I wasn't handling the file in a manner that let the program read the files contents. 问题是我没有以让程序读取文件内容的方式处理文件。 Instead it was just receiving the fake file path with the file name. 相反,它只是接收带有文件名的伪文件路径。

Fixed by utilizing @RequestParam and MultipartFile then assigning to the object before passing to the DAO. 通过利用@RequestParam和MultipartFile进行修复,然后在传递给DAO之前分配给对象。

RESTController.java RESTController.java

@PostMapping("/technologyList")
public String uploadMultipartFile(@RequestParam("logo") MultipartFile file, @RequestParam("techName")String techName) {
    User user = userService.findByUsername("wmangram");
    try {
        // save file to MySQL
        Skills newSkill = new Skills(techName, file.getBytes(), user);
        skillsService.createTechnology(newSkill);
        return "File uploaded successfully! -> filename = " + file.getOriginalFilename();
    } catch (Exception e) {
        return "FAIL! Maybe You had uploaded the file before or the file's size > 500KB";
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM