springboot向客户端输出图片 springboot接收图片_Data

============================================================== 

springboot向客户端输出图片 springboot接收图片_springboot向客户端输出图片_02

 pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.1</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>demo_upimg</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>demo_upimg</name>
    <description>demo_upimg</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>com.vaadin.external.google</groupId>
            <artifactId>android-json</artifactId>
            <version>0.0.20131108.vaadin1</version>
            <scope>compile</scope>
        </dependency>

        <!--图片文本同时传递所需的四个依赖包-->
        <!-- https://mvnrepository.com/artifact/commons-io/commons-io有关图片文本同时上传 -->
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.4</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.3</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/commons-collections/commons-collections -->
        <dependency>
            <groupId>commons-collections</groupId>
            <artifactId>commons-collections</artifactId>
            <version>3.1</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/commons-beanutils/commons-beanutils -->
        <dependency>
            <groupId>commons-beanutils</groupId>
            <artifactId>commons-beanutils</artifactId>
            <version>1.9.2</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

启动类

package com.example.demo_upimg;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class DemoUpimgApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoUpimgApplication.class, args);
    }

}

===========================

上传单张图片

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>上传单张图片原生</title>
</head>

<body>
<h2>http://localhost:8080/up1img.html</h2>
<input type="file" id="file" style="display: none;">
<button id="btn">upload</button>
</body>
<script>
    let btn = document.querySelector('#btn')
    let file = document.querySelector('#file')

    btn.onclick = function () {
        file.click() // 调取系统选择图片的弹框
    }

    // 监听input的file变化值
    file.onchange = function (event) {
        let file = event.target.files[0]
        upload(file)
    }

    function upload(file) {
        let xhr = new XMLHttpRequest()
        xhr.open('post', '/up1img', true)
        let formData = new FormData()
        formData.set('filename', file)
        xhr.send(formData)
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4 && xhr.status === 200) {
                alert('success')
            }
        }
    }
</script>

</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>上传单张图片原生</title>
</head>

<body>
<h2>方法2</h2>
<h2>http://localhost:8080/up1img2.html</h2>
<input type="file" id="file">
<button id="btn">upload</button>
</body>
<script>
    let btn = document.querySelector('#btn')

    btn.onclick = function () {
        let file = document.querySelector('#file').files[0]
        upload(file)

        function upload(file) {
            let xhr = new XMLHttpRequest()
            xhr.open('post', '/up1img', true)
            let formData = new FormData()
            formData.set('filename', file)
            xhr.send(formData)
            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4 && xhr.status === 200) {
                    alert('success')
                }
            }
        }
    }
</script>

</html>
package com.example.demo_upimg.up1img;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;


@Controller
@RequestMapping
public class Up1img {
    @PostMapping("/up1img")
    @ResponseBody
    public void up1img(
            @RequestParam(value = "filename", required = false) MultipartFile file
    ) {
        System.out.println("收到了请求上传单张图片==");
        System.out.println(file);
        if (file.isEmpty()) {
            return;
        }
        String fileName = file.getOriginalFilename();
        File dest = new File(new File("E:\\Zimg").getAbsolutePath() + "/" + fileName);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        try {
            file.transferTo(dest); // 保存文件
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

 =====================================

上传多张图片

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>

<body>
<h2>多张图片上传 单张10M以下的 PNG、JPG、GIF 格式的图片</h2>
<form action="/upnimg" method="post" enctype="multipart/form-data">
    选择文件:<input type="file" name="file">

    选择文件:<input type="file" name="file">

    选择文件:<input type="file" name="file">
    <input type="submit" value="上传多张">
</form>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>上传单张图片原生</title>
</head>

<body>
<h2>方法2</h2>
<h2>http://localhost:8080/upnimg2.html</h2>
<input type="file" class="file" name="file" multiple="multiple"/>
<br>
</body>
<script>

    document.querySelector('.file').addEventListener('change', function (e) {
        let files = e.target.files
        if (!files.length) return
        // 上传文件 创建FormData
        let formData = new FormData()
        // 遍历FileList对象,拿到多个图片对象
        for (let i = 0; i < files.length; i++) {
            // formData中的append方法 如果已有相同的键,则会追加成为一个数组  注意:这里需要使用formData.getAll()获取
            formData.append('file', files[i], files[i].name)
        }
        console.log(formData.getAll('file'))
        // 将formdata发送到后台即可
        // 发起请求
        let xhr = new XMLHttpRequest()
        xhr.open('post', '/upnimg', true)
        xhr.send(formData)
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4 && xhr.status === 200) {
                alert('success')
            }
        }
    })
</script>

</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>上传单张图片原生</title>
</head>

<body>
<h2>方法2</h2>
<h2>http://localhost:8080/upnimg3.html</h2>
<input type="file" class="file" name="file" multiple="multiple"/>
<br>
<button id="btn">upload</button>
</body>
<script>
    // 上传文件 创建FormData
    let formData = new FormData()

    //将选择的文件放入formData
    document.querySelector('.file').addEventListener('change', function (e) {
        let files = e.target.files
        if (!files.length) return
        // 遍历FileList对象,拿到多个图片对象
        for (let i = 0; i < files.length; i++) {
            // formData中的append方法 如果已有相同的键,则会追加成为一个数组  注意:这里需要使用formData.getAll()获取
            formData.append('file', files[i], files[i].name)
        }
        console.log(formData.getAll('file'))

    })

    //点击按钮发起请求
    let btn = document.querySelector('#btn')
    btn.onclick = function () {
        // 将formdata发送到后台即可
        // 发起请求
        let xhr = new XMLHttpRequest()
        xhr.open('post', '/upnimg', true)
        xhr.send(formData)
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4 && xhr.status === 200) {
                alert('success')
            }
        }
    }

</script>

</html>
package com.example.demo_upimg.upNimg;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


@Controller
@RequestMapping
public class UpNimg {
    @ResponseBody
    @RequestMapping(value = "/upnimg", method = {RequestMethod.GET, RequestMethod.POST})
    public void imageUploa(@RequestParam("file") MultipartFile[] file,
                           HttpServletRequest request, HttpServletResponse response, HttpSession session)
            throws IllegalStateException, IOException {
        System.out.println("收到一个上传多张图片的请求");
        List list = new ArrayList();
        // String images =  imageUtil.ImageUpload(file, request,response,session);
        if (file != null && file.length > 0) {
            //循环获取file数组中得文件
            for (int i = 0; i < file.length; i++) {
                MultipartFile files = file[i];
                //保存文件
                if (files.isEmpty()) {
                    return;
                }
                String fileName = files.getOriginalFilename();
                File dest = new File(new File("E:\\Zimg").getAbsolutePath() + "/" + i + fileName);
                if (!dest.getParentFile().exists()) {
                    dest.getParentFile().mkdirs();
                }
                try {
                    files.transferTo(dest); // 保存文件
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

=============================

同时上传多张文件(图片等任意文件)和文本

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>

<body>
<h2>文本和多文件上传,访问路径如下</h2>
<h2>http://localhost:8080/upTextandImg.html</h2>

<form action="/upTextandImg" method="post" enctype="multipart/form-data">
    <a>宠物(或产品)类型:</a>
    <select id="categoryID" name="cid">
        <option value="1">11</option>
        <option value="2">22</option>
        <option value="3">33</option>
    </select>
    <br/>
    <br/>
    <a>宠物(或产品)名字:</a><input type="text" name="cname"><br/><br/>
    <a>一句话介绍:</a><input type="text" name="introduction"><br/><br/>
    <a>题目:</a><input type="text" name="title"><br/><br/>
    <a>价钱:</a><input type="text" name="price"><br/><br/>
    <a>库存:</a><input type="text" name="stock"><br/><br/>
    <a>状态:</a>
    <select name="status">
        <option value="1">在售</option>
        <option value="2">下架</option>
        <option value="3">删除</option>
    </select>

    <br/><br/>
    <a>文件1:</a><input type="file" onchange="previewFile()" name="fileName1">
    <a>文件2:</a><input type="file" onchange="previewFile()" name="fileName2">
    <a>文件3:</a><input type="file" onchange="previewFile()" name="fileName3">
    <br/>
    <div id="editor">
        <p>商品详细描述</p>
        <input type="text" name="details" id="detail">
    </div>
    <br/><br/>
    <input type="submit" value="新增商品">
</form>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>上传单张图片原生</title>
</head>

<body>
<h2>方法2</h2>
<h2>http://localhost:8080/upTextandImg2.html</h2>
<input type="file" class="file" name="file" multiple="multiple"/>
<a>价钱:</a><input type="text" name="price" id="price"><br/><br/>
<br>
<button id="btn">upload</button>
</body>
<script>
    // 上传文件 创建FormData
    let formData = new FormData()

    //将选择的文件放入formData
    document.querySelector('.file').addEventListener('change', function (e) {
        let files = e.target.files
        if (!files.length) return
        // 遍历FileList对象,拿到多个图片对象
        for (let i = 0; i < files.length; i++) {
            // formData中的append方法 如果已有相同的键,则会追加成为一个数组  注意:这里需要使用formData.getAll()获取
            formData.append('file', files[i], files[i].name)
        }
        console.log(formData.getAll('file'))

    })

    //点击按钮发起请求
    let btn = document.querySelector('#btn')
    btn.onclick = function () {
        //获取文本框的值,并添加进formData
        let price = document.querySelector('#price')
        formData.append("price", price.value)

        // 将formdata发送到后台即可
        // 发起请求
        let xhr = new XMLHttpRequest()
        xhr.open('post', '/upTextandImg', true)
        xhr.send(formData)
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4 && xhr.status === 200) {
                alert('success')
            }
        }
    }

</script>

</html>
package com.example.demo_upimg.upTextandImg;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.File;
import java.io.IOException;
import java.util.*;


@Controller
@RequestMapping
public class UpImgAndText {
    @PostMapping("/upTextandImg")
    public void addPro(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("收到上传请求");
        //只获取非文件内容
        getParm(request);
        //同时获取非文件和文件内容
        getFileAndImgAndParm(request);
    }

    private void getFileAndImgAndParm(HttpServletRequest request) throws ServletException, IOException {
        System.out.println("//获取文件并保存==================");
        //将当前上下文初始化给  CommonsMutipartResolver (多部分解析器)
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(
                request.getSession().getServletContext());
        // 判断是否是多数据段提交格式
        if (multipartResolver.isMultipart(request)) {
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest) request;

            System.out.println("以下获取上传的非文件==");
            Map<String, String[]> parameterMap = multiRequest.getParameterMap();
            Set<String> keySet = parameterMap.keySet();
            for (String key : keySet) {
                String[] strings = parameterMap.get(key);
                String msg = Arrays.toString(strings);
                System.out.println(key + "===" + msg);
            }

            System.out.println("以下获取上传的文件==");
            Iterator<String> iter = multiRequest.getFileNames();
            //进入到这。iter中的已经全部是文件类型了
            Integer fileCount = 0;
            while (iter.hasNext()) {
                String next = iter.next();
                Part part = multiRequest.getPart(next);
                String name = part.getName();
                System.out.println(name);
                //TODO
                MultipartFile file = multiRequest.getFile(next);
                System.out.println(file);
                if (file == null) {
                    System.out.println("非文件");
                    return;
                }
                String fileName = UUID.randomUUID() + file.getOriginalFilename();
                File dest = new File(new File("E:\\Zimg").getAbsolutePath() + "/" + fileName);
                if (!dest.getParentFile().exists()) {
                    //新建空白图片
                    dest.getParentFile().mkdirs();
                }
                try {
                    //将图片流写入空白文件
                    file.transferTo(dest); // 保存文件
                    fileCount++;
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            System.out.println("本次提交文件类型的个数==" + fileCount);
        }
    }

    private void getParm(HttpServletRequest request) {
        System.out.println("两种方法获取非文件类型的值");
        //获取非文件并保存==========================================================================
        Map<String, String> parmMap = new HashMap<String, String>();
        //方式一:getParameterMap(),获得请求参数map
        Map<String, String[]> map = request.getParameterMap();
        //参数名称
        Set key = map.keySet();
        //参数迭代器
        Iterator iterator = key.iterator();
        while (iterator.hasNext()) {
            String k = String.valueOf(iterator.next());
            parmMap.put(k, map.get(k)[0]);
        }
        System.out.println("parmMap==========" + parmMap);

        //方式二:getParameterNames():获取所有参数名称
        Enumeration a = request.getParameterNames();
        String parm = null;
        String val = "";
        while (a.hasMoreElements()) {
            //参数名
            parm = String.valueOf(a.nextElement());
            //值
            val = request.getParameter(parm);
            parmMap.put(parm, val);
        }
        System.out.println("parmMap==========" + parmMap);
    }
}

springboot向客户端输出图片 springboot接收图片_Data_03

=======================================

补充

前端通过formdata上传

后端直接通过对象接收文本数据,使用MultipartFile[  ] 接收多个文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>上传单张图片原生</title>
</head>

<body>
<h2>方法2</h2>
<h2>http://localhost:8080/upTextandImg3.html</h2>
<input type="file" class="file" name="file" multiple="multiple"/><br/><br/>

<a>产品类型:</a>
<select id="categoryID" name="cid">
    <option value="1">11</option>
    <option value="2">22</option>
    <option value="3">33</option>
</select>
<br/>
<br/>

<a>价钱:</a><input type="text" name="price" id="price"><br/><br/>
<a>库存:</a><input type="text" name="stock" id="stock"><br/><br/>
<a>状态:</a>
<select name="status" id="status">
    <option value="1">在售</option>
    <option value="2">22</option>
    <option value="3">33</option>
</select>
<br/><br/>

<p>商品详细描述</p>
<input type="text" name="details" id="detail">

<br/><br/>

<br>
<button id="btn">upload</button>
</body>
<script>
    // 上传文件 创建FormData
    let formData = new FormData()

    //将选择的文件放入formData
    document.querySelector('.file').addEventListener('change', function (e) {
        let files = e.target.files
        if (!files.length) return
        // 遍历FileList对象,拿到多个图片对象
        for (let i = 0; i < files.length; i++) {
            // formData中的append方法 如果已有相同的键,则会追加成为一个数组  注意:这里需要使用formData.getAll()获取
            formData.append('file', files[i], files[i].name)
        }
        console.log(formData.getAll('file'))

    })

    //点击按钮发起请求
    let btn = document.querySelector('#btn')
    btn.onclick = function () {
        //获取文本框的值,并添加进formData
        let categoryID = document.querySelector('#categoryID')
        formData.append("categoryID", categoryID.value)
        let price = document.querySelector('#price')
        formData.append("price", price.value)
        let stock = document.querySelector('#stock')
        formData.append("stock", stock.value)
        let status = document.querySelector('#status')
        formData.append("status", status.value)
        let detail = document.querySelector('#detail')
        formData.append("detail", detail.value)


        // 将formdata发送到后台即可
        // 发起请求
        let xhr = new XMLHttpRequest()
        xhr.open('post', '/movements', true)
        xhr.send(formData)
        xhr.onreadystatechange = function () {
            if (xhr.readyState === 4 && xhr.status === 200) {
                alert('success')
            }
        }
    }

</script>

</html>
package com.example.demo_upimg.upTextandImg;

public class Movement {
    private String categoryID;
    private String price;
    private String stock;
    private String status;
    private String detail;

    @Override
    public String toString() {
        return "Movement{" +
                "categoryID='" + categoryID + '\'' +
                ", price='" + price + '\'' +
                ", stock='" + stock + '\'' +
                ", status='" + status + '\'' +
                ", detail='" + detail + '\'' +
                '}';
    }

    public String getCategoryID() {
        return categoryID;
    }

    public void setCategoryID(String categoryID) {
        this.categoryID = categoryID;
    }

    public String getStock() {
        return stock;
    }

    public void setStock(String stock) {
        this.stock = stock;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    public String getDetail() {
        return detail;
    }

    public void setDetail(String detail) {
        this.detail = detail;
    }

    public String getPrice() {
        return price;
    }

    public void setPrice(String price) {
        this.price = price;
    }
}
package com.example.demo_upimg.upTextandImg;

import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.UUID;

@RestController
@RequestMapping("/movements")
public class UpImgAndText3 {
    /**
     * 发布动态,从mongo sequence获取自增PID,再保存
     */
    @PostMapping
    public ResponseEntity movements(Movement movement,
                                    MultipartFile[] file) {
        //file这个名字要和前端页面一致,否则要额外注明。此处对应的前端为<input type="file" class="file" name="file" multiple="multiple"/><br/><br/>

        System.out.println("收到请求==");
        System.out.println("接收文本数据=" + movement);
        System.out.println("接收文件数据=" + file);

        Integer fileCount = 0;
        for (MultipartFile multipartFile : file) {
            System.out.println(multipartFile);
            if (multipartFile == null) {
                System.out.println("非文件");
            }
            String fileName = UUID.randomUUID() + multipartFile.getOriginalFilename();
            File dest = new File(new File("E:\\Zimg").getAbsolutePath() + "/" + fileName);
            if (!dest.getParentFile().exists()) {
                //新建空白图片
                dest.getParentFile().mkdirs();
            }
            try {
                //将图片流写入空白文件
                multipartFile.transferTo(dest); // 保存文件
                fileCount++;
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
        System.out.println("本次提交文件类型的个数==" + fileCount);
        return ResponseEntity.ok(null);
    }

}

springboot向客户端输出图片 springboot接收图片_Data_04

springboot向客户端输出图片 springboot接收图片_后端_05

 =============================