jsp部分:
<form id="upform">
<div class="form-group has-success col-md-4">
<label class="control-label" for="inputSuccess1">新商品名称</label>
<input type="text" class="form-control" name="agname" id="agname">
</div>
<div class="form-group has-success col-md-4">
<div style="margin-left: 18px; margin-bottom: 15px;">
<label style="color: green;" class="control-label" for="inputWarning1">上传图片</label>
<input type="file" name="file" id="upfile" style="width: 200px;height: 40px;border-radius: 5px;" >
<input style="width: 80px;height: 40px;border-radius: 5px;background-color: rgb(53,167,232);border: 0px;"
type="button" value="上传" οnclick="upNewGoods()"></input>
</div>
</form>
js部分:
// 添加新商品
function upNewGoods() {
var formData = new FormData($("#upform")[0]);
$.ajax({
url : 'UpGoodsImg',
type : 'post',
data : formData,
async : false,
cache : false,
contentType : false,
processData : false,
success : function(result) {
if (result == 1) {
$("#mainborder").load("student/addInterview.jsp");
$("#adderrormsg").val("添加成功!");
$("#addNewErrorModal").modal('show');
} else {
$("#adderrormsg").val("添加失败!");
$("#addNewErrorModal").modal('show');
}
},
error:function(){
$("#adderrormsg").val("请完善新增信息");
$("#addNewErrorModal").modal('show');
}
});
}
底层servlet部分:
@WebServlet("/UpGoodsImg")
@MultipartConfig //此处需要添加注解才可以获取文件对象,注解仅支持servlet3.0版本以上,低版本需要依赖相关jar包
public class UpGoodsImg extends HttpServlet {
private static final long serialVersionUID = 1L;
private IGoodsService goodsService = new GoodsServiceImpl();
/**
* @see HttpServlet#HttpServlet()
*/
public UpGoodsImg() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
* response)
*/
// 添加新商品addNewGoods
protected void doGet(HttpServletRequest request, HttpServletResponse res) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
(。。。)//此处省去获取普通数据
Part part = request.getPart("file");//获取文件对象,此处的“file”为jsp部分文件输入框的name属性值
String filePath = FileUploadByQiNiu.fileUp(part);//实现七牛云接口封装的方法,在下方介绍,完成上传至文件服务器,并返回文件相对存储地址,此处用的是七牛云文件服务器,
if (filePath != null) {
String img_url = "http://oxr7ibv5k.bkt.clouddn.com/" + filePath;//拼接完整的文件地址,方便存入数据库中。
System.out.println(img_url);
Goods goods = new Goods(gname, gcount, price, cost, introduction, new Kinds(kid), img_url);
int result = goodsService.addNewGoods(goods);//插入数据库底层调用
if (result == 1) {
res.getWriter().write("1");
} else {
res.getWriter().write("0");
}
}
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
实现七牛云文件服务器接口
import java.io.IOException;
import javax.servlet.http.Part;
import com.google.gson.Gson;
//以下jar包请参考七牛云开发手册下载相关jar包
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
public class FileUploadByQiNiu {
public static String fileUp(Part part) {
Configuration cfg = new Configuration(Zone.zone0());// 华东机房
UploadManager uploadManager = new UploadManager(cfg);
String accessKey = "f0lvMKJlgevM3ARKx2EA0ho4uevDoOOE3R75L-**";//替换成你七牛云的用户名和秘钥
String secretKey = "nv5X98ed8CCHFwKZPA-7zsntwWT52Z-ax7z-dc**";
String bucket = "friutstore";// 替换成你的空间名
Auth auth = Auth.create(accessKey, secretKey);
String upToken = auth.uploadToken(bucket);
System.out.println(upToken);// 上传凭证 认证身份
// 如果是Windows情况下,格式是 D:\\qiniu\\test.png
// 默认不指定key的情况下,以文件内容的hash值作为文件名,可避免文件名重复,但文件名不好看
String key = null;
String filePath = null;
try {
Response response = null;
try {
response = uploadManager.put(part.getInputStream(), key, upToken, null, null);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 解析上传成功的结果
DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
filePath = putRet.key;// 返回的文件名
System.out.println(putRet.hash);// 哈希值
} catch (QiniuException ex) {
Response r = ex.response;
System.err.println(r.toString());
try {
System.err.println(r.bodyString());
} catch (QiniuException ex2) {
// ignore
}
}
return filePath;
}
}