先上一张图片
仅说下上传文件,完整的项目请到我的个人中心下载https://download.csdn.net/my
html页面代码
<form method="post" class="form-x" action="ProductServlet.do?dowhat=addpro"
enctype="multipart/form-data">
<div class="form-group">
<div class="label">
<label>商品图片:</label>
</div>
<div class="field">
<input type="file" id="url1" name="proimg" class="input tips"
style="width:25%; float:left;" value="" data-toggle="hover"
data-place="right" data-image="" />
<div class="tipss">图片尺寸:500*500</div>
</div>
</div>
</form>
enctype="multipart/form-data" 这个是关键!!!!
servle代码
@MultipartConfig
这个注解一定要有,分部上传
Part part=req.getPart("perimg");
String path=req.getServletContext().getRealPath("img");
String imgpath=service.uploadImg(part, path);
String perimg=null;
if (imgpath==null) {
resp.getWriter().print("文件格式或者大小不正确");
System.out.println("文件格式或者大小不正确");
return;
}else {
perimg=imgpath;
}
UploadImg方法
//上传文件
public String uploadImg(Part part,String path) {
//2.3通过文件的content-type,判断文件的类型
String type=part.getContentType();
if (!(type.contains("png")||type.contains("pneg")||type.contains("jpg")||type.contains("jpeg")||type.contains("gif"))) {
//返回前端文件必须是指定格式
return null;
}
//2.4判断文件大小
if (part.getSize()>1000*1024) {
return null;
}
//2.5将文件进行拼接写入到指定文件
//处理字符串,获取上传的文件名
String content=part.getHeader("content-disposition");
String filename=content.substring(content.lastIndexOf("=\"")+2,content.lastIndexOf("\""));
String newFile="img/"+filename;
File file=new File(path);
if (!file.exists()) {
file.mkdir();
}
filename=path+File.separatorChar+filename;
//2.6将文件写到指定位置
try {
part.write(filename);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return newFile;
}