在我的上一篇博客中,介绍了关于异步上传图片的代码,下面我就来介绍一下服务端怎样去接收图片,并将图片插入数据库。
首先,图片上传的本质还是以流的方式,上传的时候是将图片转化成字节,对图片进行压缩后在进行上传(压缩部分没写),那么,在服务端接收的时候就是将字节转化成图片信息,另外,在上传图片的时候还携带了部分的数据,在接收的时候也会对应的接收。
这是我在完成的项目中摘出来上传商品的图片和视频的一部分代码,供大家学习参考。
注意:部分类是需要导架包的。
下面我就直接上代码:
实体类:
package com.sh.bean;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "listview")
public class Listview {
private String id;
private String user;//上传用户名
private String goodsphtotourl;//展示主图
private String goodsname;//商品名
private String goodsdetail;//商品描述
private String goodsprice;//商品价格
private String goodscode;//商品序列号
private String goodsphotogroup;//商品图片组
private String goodstype;//商品类型
private String goodsvideo;//商品视频
public String getGoodsvideo() {
return goodsvideo;
}
public void setGoodsvideo(String goodsvideo) {
this.goodsvideo = goodsvideo;
}
public String getGoodsphotogroup() {
return goodsphotogroup;
}
public void setGoodsphotogroup(String goodsphotogroup) {
this.goodsphotogroup = goodsphotogroup;
}
public String getGoodstype() {
return goodstype;
}
public void setGoodstype(String goodstype) {
this.goodstype = goodstype;
}
public String getGoodscode() {
return goodscode;
}
public void setGoodscode(String goodscode) {
this.goodscode = goodscode;
}
@Id
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getGoodsphtotourl() {
return goodsphtotourl;
}
public void setGoodsphtotourl(String goodsphtotourl) {
this.goodsphtotourl = goodsphtotourl;
}
public String getGoodsname() {
return goodsname;
}
public void setGoodsname(String goodsname) {
this.goodsname = goodsname;
}
public String getGoodsdetail() {
return goodsdetail;
}
public void setGoodsdetail(String goodsdetail) {
this.goodsdetail = goodsdetail;
}
public String getGoodsprice() {
return goodsprice;
}
public void setGoodsprice(String goodsprice) {
this.goodsprice = goodsprice;
}
}
这是接收商品信息和图片的类:
package com.sh.action;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.List;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.sh.bean.Listview;
import com.sh.common.UUIDUtils;
import com.sh.service.UploadgoodsService;
import com.sh.util.UploadPhoto;
import net.sf.json.JSONObject;
@Controller("UploadgoodsController")
@RequestMapping("/Uploadgoods")
public class UploadgoodsController {
@Resource(name = "uploadgoodsService")
private UploadgoodsService uploadgoodsService;
StringBuffer secondstringBuffer = new StringBuffer();// 存放图片组的字符串
StringBuffer mainshowphotoBuffer = new StringBuffer();// 存放主图的字符串
StringBuffer mainshowvideoBuffer = new StringBuffer();// 存放主视频的字符串
Listview listview = new Listview();
@RequestMapping("/index")
public ModelAndView login() {
ModelAndView mv = new ModelAndView("/index");
return mv;
}
/**
* 上传商品信息
*/
@RequestMapping("/uploadgoods.do")
public void uploadgoods(HttpServletRequest request, HttpServletResponse response) throws Exception {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
/*
* 上传商品图片,视频
*/
uploadgoodsphoto(request);
Boolean upload = uploadgoodsService.uploadgoods(listview);
if (upload) {
response.getWriter().print("商品信息上传成功!");
} else {
response.getWriter().print("商品信息上传失败!");
}
}
/**
* 上传商品图片,视频
*/
public void uploadgoodsphoto(HttpServletRequest request) throws Exception {
/*
* 得到商品相关参数
*/
// 生成商品订单号
String goodscode = UploadPhoto.getgoodscode();
// 上传商品时间
String nowtime = UploadPhoto.getnowtime();
// //上传商品名
String goodsname = null;
// //商品价格
String goodsprice = null;
// //商品描述
String goodsdetail=null;
// //上传商品用户
String user=null;
// //商品种类
String goodstype=null;
// //商品图片的种类
String uploadtype = null;
// 获得磁盘文件条目工厂。
DiskFileItemFactory factory = new DiskFileItemFactory();
// 获取文件上传需要保存的路径,upload文件夹需存在。
String path = "";
// 设置暂时存放文件的存储室,这个存储室可以和最终存储文件的文件夹不同。因为当文件很大的话会占用过多内存所以设置存储室。
factory.setRepository(new File(path));
// 设置缓存的大小,当上传文件的容量超过缓存时,就放到暂时存储室。
factory.setSizeThreshold(1024 * 1024 * 150);
// 上传处理工具类(高水平API上传处理?)
ServletFileUpload upload = new ServletFileUpload(factory);
try {
// 调用 parseRequest(request)方法 获得上传文件 FileItem 的集合list 可实现多文件上传。
List<FileItem> list = (List<FileItem>) upload.parseRequest(request);
for (FileItem item : list) { // 遍历传过来的文件
// 获取表单属性名字。
String name = item.getFieldName();
// 如果获取的表单信息是普通的文本信息。即通过页面表单形式传递来的字符串。
if (name.contains("content")) {
InputStream in = item.getInputStream();
// System.out.println("获取的字符串:"+inputStream2String(in));
JSONObject jo = JSONObject.fromObject(inputStream2String(in));
user = jo.getString("user");
uploadtype = jo.getString("uploadtype");
goodsname=jo.getString("goodsname");
goodsprice=jo.getString("goodsprice");
goodsdetail=jo.getString("goodsdetail");
goodstype=jo.getString("goodstype");
System.out.println("获取的name字符串:" + user);
System.out.println("获取的uploadtype字符串:" + uploadtype);
System.out.println("获取的goodstype字符串:" + goodstype);
/*
* 接收图片存放地址
*/
String mainphotopath = "F:wujiescl/upload/" + user + "/" + nowtime + "/mainphoto"; // 商品封面展示图
String showphotopath = "D:upload/" + user + "/" + nowtime + "/showphoto";// 商品图集(用于商品详情页轮播)
String showvideopath = "F:wujiescl/upload/" + user + "/" + nowtime + "/showvideo";// 商品视频
if (uploadtype.equals("mainphoto")) {
path = mainphotopath;
} else if (uploadtype.equals("showphoto")) {
System.out.println("创建了文件夹啊!");
path = showphotopath;
File file2 = new File(path);
if (!file2.exists()) {
file2.mkdirs();
}
} else if (uploadtype.equals("showvideo")) {
path = showvideopath;
}
}
if (item.isFormField()) {
// 获取用户具体输入的字符串,
String value = item.getString();
}
// 如果传入的是非简单字符串,而是图片,音频,视频等二进制文件。
else {
// 获取路径名
String value = item.getName();
// 取到最后一个反斜杠。
int start = value.lastIndexOf("\\");
// 截取上传文件的 字符串名字。+1是去掉反斜杠。
String filename = value.substring(start + 1);
request.setAttribute(name, filename);
//将上传的图片组转化成字符串
if(uploadtype.equals("showphoto")){
secondstringBuffer.append("F:wujiescl/upload/"+"/"+filename);
secondstringBuffer.append("====");
}else if(uploadtype.equals("mainphoto")){ //将上传的主图转化成字符串
mainshowphotoBuffer.append("F:wujiescl/upload/"+"/"+filename);
}
else if(uploadtype.equals("showvideo")){//将上传的视频转化成字符串
mainshowvideoBuffer.append("F:wujiescl/upload/"+"/"+filename);
}
/*
* 第三方提供的方法直接写到文件中。 item.write(new File(path,filename));
*/
// 收到写到接收的文件中。
OutputStream out = new FileOutputStream(new File(path, filename));
InputStream in = item.getInputStream();
int length = 0;
byte[] buf = new byte[1024];
System.out.println("获取文件总量的容量:" + item.getSize());
while ((length = in.read(buf)) != -1) {
out.write(buf, 0, length);
}
in.close();
out.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
/*
* 将商品信息插入数据库
*/
listview.setGoodsphtotourl("11111111111");//主图访问路径
listview.setGoodsname(goodsname);
listview.setGoodsprice(goodsprice);
listview.setGoodsdetail(goodsdetail);
listview.setUser(user);
listview.setGoodstype(goodstype);
listview.setGoodscode(goodscode);
listview.setGoodsvideo("54415151");//视频访问路径
listview.setGoodsphotogroup(secondstringBuffer.toString());
listview.setId(UUIDUtils.create().toString());
}
// 流转化成字符串
public static String inputStream2String(InputStream is) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int i = -1;
while ((i = is.read()) != -1) {
baos.write(i);
}
byte[] temp=baos.toString().trim().getBytes("gbk");//这里写原编码方式
String newStr=new String(temp,"utf-8");//这里写转换后的编码方式
return newStr;
}
// 流转化成文件
public static void inputStream2File(InputStream is, String savePath) throws Exception {
System.out.println("文件保存路径为:" + savePath);
File file = new File(savePath);
InputStream inputSteam = is;
BufferedInputStream fis = new BufferedInputStream(inputSteam);
FileOutputStream fos = new FileOutputStream(file);
int f;
while ((f = fis.read()) != -1) {
fos.write(f);
}
fos.flush();
fos.close();
fis.close();
inputSteam.close();
}
/**
* 方法名称:transStringToMap 传入参数:mapString 形如 username'chenziwen^password'1234
* 返回值:Map
*/
public static HashMap<String, String> mapStringToMap(String str) {
System.out.println("www:" + str);
String str1 = str.substring(1, str.length() - 1);
System.out.println("www的值::" + str1);
String[] strs = str1.split(",");
System.out.println("www的值www::" + strs[0] + "ddd:" + strs[1]);
HashMap<String, String> map = new HashMap<String, String>();
for (String string : strs) {
String key = string.split("=")[0];
System.out.println("key的值:" + key);
String value = string.split("=")[1];
System.out.println("value的值:" + value);
map.put(key, value);
}
return map;
}
}
在上面代码中,是在本地进行测试的,所以保存的路径也就在本地,大家可以根据自己的需求进行修改。android上传商品信息代码请参考我的博客: