==============================================================
pom.xml
4.0.0
org.springframework.boot
spring-boot-starter-parent
2.6.1
com.example
demo_upimg
0.0.1-SNAPSHOT
demo_upimg
demo_upimg
1.8
org.springframework.boot
spring-boot-starter-web
org.springframework.boot
spring-boot-starter-test
test
com.vaadin.external.google
android-json
0.0.20131108.vaadin1
compile
commons-io
commons-io
2.4
commons-fileupload
commons-fileupload
1.3.3
commons-collections
commons-collections
3.1
commons-beanutils
commons-beanutils
1.9.2
org.springframework.boot
spring-boot-maven-plugin
启动类
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);
}
}
===========================
上传单张图片
上传单张图片原生
http://localhost:8080/up1img.html
上传单张图片原生
方法2
http://localhost:8080/up1img2.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();
}
}
}
=====================================
上传多张图片
Title
多张图片上传 单张10M以下的 PNG、JPG、GIF 格式的图片
上传单张图片原生
方法2
http://localhost:8080/upnimg2.html
上传单张图片原生
方法2
http://localhost:8080/upnimg3.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();
}
}
}
}
}
=============================
同时上传多张文件(图片等任意文件)和文本
Title
文本和多文件上传,访问路径如下
http://localhost:8080/upTextandImg.html
上传单张图片原生
方法2
http://localhost:8080/upTextandImg2.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 parameterMap = multiRequest.getParameterMap();
Set 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 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 parmMap = new HashMap();
//方式一:getParameterMap(),获得请求参数map
Map 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);
}
}
=======================================
补充
前端通过formdata上传
后端直接通过对象接收文本数据,使用MultipartFile[ ] 接收多个文件
上传单张图片原生
方法2
http://localhost:8080/upTextandImg3.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这个名字要和前端页面一致,否则要额外注明。此处对应的前端为
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);
}
}