图片上传
项目背景:
该项目是大一暑假实验室安排的前后端练手项目。
本人负责物品增删改查和物品展示,本人选择图片展示。
开始之前:
在接触该项目之前,并没有接触过关于图片上传的东西。在网上查找了各种资料,决定了如何去写。
历程:
使用本地文件夹
最初选择把图片存到本地文件夹里,当时在resources目录下建了一个goodsImage文件夹。
因为增删改查很简单,为了体现保存图片到本地和传给前端,用展示全部物品和添加物品举例。并且只展示controller层和实体类。
controller层
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
|
@PostMapping("/getAllGoods") public GoodsResult getAllGoods(@RequestParam Integer pageNum, @RequestParam Integer pageSize){ return goodsService.getAllGoods(pageNum,pageSize); }
@PostMapping("/addGoods") public ResponseEntity<Void> addGoods(@RequestParam MultipartFile uploadImage,@RequestParam String goodsName,@RequestParam String goodsState,@RequestParam Integer goodsQuantity){ Goods goods = new Goods(); goods.setGoodsName(goodsName); goods.setGoodsState(goodsState); imageService.saveGoodsImage(uploadImage,goods); for(int i = 0;i < goodsQuantity;i++){ goodsService.addGoods(goods); } return ResponseEntity.status(HttpStatus.CREATED).build(); }
|
ImageServiceImpl
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
| package com.lc.demo.service.impl;
import com.lc.demo.bean.Goods; import com.lc.demo.service.ImageService; import org.springframework.boot.ApplicationHome; import org.springframework.stereotype.Service; import org.springframework.util.ClassUtils; import org.springframework.web.multipart.MultipartFile; import java.io.File; import java.io.IOException; import java.util.UUID;
@Service public class ImageServiceImpl implements ImageService { @Override public void saveGoodsImage(MultipartFile uploadImage, Goods goods) {
String fileName = UUID.randomUUID().toString() + ".jpg"; String staticPath = ClassUtils.getDefaultClassLoader().getResource("goodsImage").getPath() + File.separator+ fileName;
try { uploadImage.transferTo(new File(staticPath)); goods.setGoodsImage( "/goodsImage/" + fileName);
} catch (IOException e) { e.printStackTrace(); } } }
|
GoodsResult
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
| package common;
import com.github.pagehelper.PageInfo;
import com.lc.demo.bean.Goods; import org.apache.ibatis.io.Resources; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import java.io.ByteArrayOutputStream; import java.io.FileInputStream; import java.io.InputStream; import java.util.ArrayList; import java.util.List; import java.util.ResourceBundle;
public class GoodsResult { private PageInfo<Goods> data; private int totalPages; private List<ResponseEntity<byte[]>> responseEntityList;
public PageInfo<Goods> getData() { return data; }
public void setData(PageInfo<Goods> data) { this.data = data; }
public int getTotalPages() { return totalPages; }
public void setTotalPages(int totalPages) { this.totalPages = totalPages; }
public List<ResponseEntity<byte[]>> getResponseEntityList() { return responseEntityList; }
public void setResponseEntityList(List<ResponseEntity<byte[]>> responseEntityList) { this.responseEntityList = responseEntityList; }
public static GoodsResult pagingGoodsResult(int pageNum,int pageSize, PageInfo<Goods> pageInfo) { GoodsResult goodsResult = new GoodsResult();
long total =pageInfo.getTotal(); int totalPages = (int) Math.ceil((double) total / pageSize);
List<Goods> goodsList = pageInfo.getList(); List<ResponseEntity<byte[]>> responseEntityList = new ArrayList<ResponseEntity<byte[]>>();
if(pageNum != totalPages){ for (int i = 0; i < pageSize; i++){ responseEntityList.add(ProcessPictures(goodsList.get(i))); } }else{ for (int i = 0; i < total-pageSize*(totalPages-1); i++){ responseEntityList.add(ProcessPictures(goodsList.get(i))); } }
goodsResult.setResponseEntityList(responseEntityList); goodsResult.setData(pageInfo); goodsResult.setTotalPages(totalPages); return goodsResult; }
public static ResponseEntity<byte[]> ProcessPictures(Goods goods){ String goodsImage = goods.getGoodsImage(); InputStream inputStream = null;
try { inputStream = ClassLoader.getSystemClassLoader().getResourceAsStream(goodsImage.substring(1));
byte[] bytes = new byte[1024]; int b; ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); while((b = inputStream.read(bytes)) != -1){ byteArrayOutputStream.write(bytes,0,b); } return new ResponseEntity<>(byteArrayOutputStream.toByteArray(), HttpStatus.OK); } catch (Exception e) { e.printStackTrace(); } return null; } }
|
Goods类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
| package com.lc.demo.bean; import org.hibernate.validator.constraints.NotBlank; import javax.validation.constraints.NotNull;
public class Goods { private Integer goodsId; @NotBlank(message = "名称不能为空") private String goodsName; @NotNull(message = "状态不能为空") private String goodsState; @NotBlank(message = "图片不能为空") private String goodsImage;
public Goods() { }
public Goods(String goodsName, int goodsId, String goodsstate, String goodsImage) { this.goodsName = goodsName; this.goodsId = goodsId; this.goodsState = goodsstate; this.goodsImage = goodsImage; }
public String getGoodsName() { return goodsName; }
public void setGoodsName(String goodsName) { this.goodsName = goodsName; }
public Integer getGoodsId() { return goodsId; }
public void setGoodsId(Integer goodsId) { this.goodsId = goodsId; }
public String getGoodsState() { return goodsState; }
public void setGoodsState(String goodsState) { this.goodsState = goodsState; }
public String getGoodsImage() { return goodsImage; }
public void setGoodsImage(String goodsImage) { this.goodsImage = goodsImage; }
@Override public String toString() { return "Goods{" + "goodsId=" + goodsId + ", goodsName='" + goodsName + '\'' + ", goodsState='" + goodsState + '\'' + ", goodsImage='" + goodsImage + '\'' + '}'; } }
|
实现思路
1.用MultipartFile接收图片
2.存图片到本地文件夹
通过ImageServiceImpl将图片存到本地文件夹,具体思路有注释。
把路径存到Goods类的GoodsImage属性(String),方便以后展示取。
3.展示物品
我选择用ResponseEntity<byte[]>传给前端。
因为要同时传给前端物品其他属性以及图片以及分页的总页数,因此我定义了一个GoodsResult类把他们放到一起传给前端。
失败
这种方案在本地没有什么问题。
当我们准备把项目部署到服务器上,要把项目打包为jar包,会有源源不断的图片存入。
使用阿里云服务器
在阿里云上开通阿里云oss对象存储
上传图片到阿里云上,在码代码之前,先去开通oss,并新建一个bucket
获取参数
我们需要在阿里云上获取四个重要的参数
第一个:bucket名称
第二个:地域节点(这个看你选择的时候选择哪个的确的)
第三个: AccessKey ID
第四个:AccessKey Secret
新建一个SpringBoot工程
导入依赖
1 2 3 4 5
| <dependency> <groupId>com.aliyun.oss</groupId> <artifactId>aliyun-sdk-oss</artifactId> <version>2.8.3</version> </dependency>
|
oss工具类的编写
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209
| package common;
import org.springframework.stereotype.Component; import org.springframework.web.multipart.MultipartFile; import com.aliyun.oss.OSSClient; import com.aliyun.oss.model.ObjectMetadata; import com.aliyun.oss.model.PutObjectResult; import org.springframework.beans.factory.annotation.Value; import org.springframework.util.StringUtils; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.util.Date; import java.util.List; import java.util.Random;
@Component public class OssUtil{ private String endpoint = "........."; private String accessKeyId = "......."; private String accessKeySecret = "......."; private String bucketName = "......"; private String filedir = ".......";
public String uploadImg2Oss(MultipartFile file) { if (file.getSize() > 1024 * 1024 *20) { return "图片太大"; } String originalFilename = file.getOriginalFilename(); String substring = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase(); Random random = new Random(); String name = random.nextInt(10000) + System.currentTimeMillis() + substring; try { InputStream inputStream = file.getInputStream(); this.uploadFile2OSS(inputStream, name); return name; } catch (Exception e) { return "上传失败"; } }
private String uploadFile2OSS(InputStream instream, String fileName) { String ret = ""; try { ObjectMetadata objectMetadata = new ObjectMetadata(); objectMetadata.setContentLength(instream.available()); objectMetadata.setCacheControl("no-cache"); objectMetadata.setHeader("Pragma", "no-cache"); objectMetadata.setContentType(getcontentType(fileName.substring(fileName.lastIndexOf(".")))); objectMetadata.setContentDisposition("inline;filename=" + fileName);
OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret); PutObjectResult putResult = ossClient.putObject(bucketName, filedir + fileName, instream, objectMetadata); ret = putResult.getETag(); } catch (IOException e) { e.getMessage(); } finally { try { if (instream != null) { instream.close(); } } catch (IOException e) { e.printStackTrace(); } } return ret; }
public static String getcontentType(String FilenameExtension) { if (FilenameExtension.equalsIgnoreCase(".bmp")) { return "image/bmp"; } if (FilenameExtension.equalsIgnoreCase(".gif")) { return "image/gif"; } if (FilenameExtension.equalsIgnoreCase(".jpeg") || FilenameExtension.equalsIgnoreCase(".jpg") || FilenameExtension.equalsIgnoreCase(".png")) { return "image/jpg"; } if (FilenameExtension.equalsIgnoreCase(".html")) { return "text/html"; } if (FilenameExtension.equalsIgnoreCase(".txt")) { return "text/plain"; } if (FilenameExtension.equalsIgnoreCase(".vsd")) { return "application/vnd.visio"; } if (FilenameExtension.equalsIgnoreCase(".pptx") || FilenameExtension.equalsIgnoreCase(".ppt")) { return "application/vnd.ms-powerpoint"; } if (FilenameExtension.equalsIgnoreCase(".docx") || FilenameExtension.equalsIgnoreCase(".doc")) { return "application/msword"; } if (FilenameExtension.equalsIgnoreCase(".xml")) { return "text/xml"; } return "image/jpg"; }
public String getImgUrl(String fileUrl) { if (!StringUtils.isEmpty(fileUrl)) { String[] split = fileUrl.split("/"); String url = this.getUrl(this.filedir + split[split.length - 1]); String[] spilt1 = url.split("\\?"); return spilt1[0];
} return null; }
public String getUrl(String key) { Date expiration = new Date(System.currentTimeMillis() + 3600 * 1000 * 24 * 365 * 10); OSSClient ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret); URL url = ossClient.generatePresignedUrl(bucketName, key, expiration); if (url != null) { return url.toString(); } return null; }
public String checkList(List<MultipartFile> fileList) { String fileUrl = ""; String str = ""; String photoUrl = "InputStream inputStream = file.getInputStream(); this.uploadFile2OSS(inputStream, name); return name;//RestResultGenerator.createSuccessResult(name);"; for(int i = 0;i< fileList.size();i++){ fileUrl = uploadImg2Oss(fileList.get(i)); str = getImgUrl(fileUrl); if(i == 0){ photoUrl = str; }else { photoUrl += "," + str; } } return photoUrl.trim(); }
public String checkImage(MultipartFile file){ String fileUrl = uploadImg2Oss(file); String str = getImgUrl(fileUrl); return str.trim(); } }
|
controller
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| @PostMapping("/getAllGoods") public GoodsResult getAllGoods(@RequestParam Integer pageNum, @RequestParam Integer pageSize){ return goodsService.getAllGoods(pageNum,pageSize); }
@PostMapping("/addGoods") public ResponseEntity<Void> addGoods(@RequestParam MultipartFile uploadImage,@RequestParam String goodsName,@RequestParam String goodsState,@RequestParam Integer goodsQuantity){ String goodsImage = null; try { goodsImage = ossUtil.checkImage(uploadImage); }catch (Exception e) { e.printStackTrace(); } Goods goods = new Goods(); goods.setGoodsName(goodsName); goods.setGoodsState(goodsState); goods.setGoodsImage(goodsImage);
for(int i = 0;i < goodsQuantity;i++){ goodsService.addGoods(goods); } return ResponseEntity.status(HttpStatus.CREATED).build(); }
|
思路
前端传来图片后直接保存到阿里云服务器,然后把url存到Goods类goodsImage里,到时候直接给前端传Goods即可,方便许多。
前端
1 2 3 4 5
| <div> <a href="javascript:void(0)" onclick="uploadPhoto()">选择图片</a> <input type="file" id="coverUrl" name="coverUrl" style="display: none;" onchange="upload()"> <img id="preview_photo" src="" width="200px" height="200px"> </div>
|
1 2 3
| function uploadPhoto() { $("#coverUrl").click(); }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
| function upload() { if ($("#coverUrl").val() == '') { return; } console.log("图片上传...") var formData = new FormData(); formData.append('file', document.getElementById('coverUrl').files[0]); $.ajax({ url: "/homeImageUpload", type: "post", data: formData, contentType: false, processData: false, success: function (data) { console.log(data); if (data != null) { $("#preview_photo").attr("src", data); } else { alert("上传失败"); } }, error: function (data) { alert("上传失败") } }); }
|
评论区
欢迎你留下宝贵的意见,昵称输入QQ号会显示QQ头像哦~