一个图片上传的servlet,传到本地磁盘,要传到服务器请修改

本来想写个controller,结果拦截器把图片拦住了,那就直接servlet

 

public class UploadEamge extends HttpServlet{

/**
*
*/
private static final long serialVersionUID = 1L;
private static final String[] IMAGE_TYPE = new String[] {".bmp",".jpeg",".jpg",".gif",".png"};

public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// 校验图片格式
DiskFileItemFactory factory = new DiskFileItemFactory();
String uploadTempDir="E:/123";
factory.setRepository(new File(uploadTempDir));
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setHeaderEncoding("utf-8");
List<FileItem> fileList;
try {
fileList = upload.parseRequest(request);
response.setCharacterEncoding("utf-8");
String uuidName=null;
Iterator<FileItem> it= fileList.iterator();
String filePath="E:/123";
File newFile = new File(filePath);
if (!newFile.exists()) {
newFile.mkdirs();// E:\all_apaches\apache-tomcat-6.0.32\apache-tomcat-6.0.32\webapps\day09_upload\img
}
while (it.hasNext()) {
FileItem item = it.next();
if (!item.isFormField()) {

String name = item.getName();
long size = item.getSize();

if (name == null || name.trim().equals("")) {
continue;
}
try {
if (size > 716800) {
response.getWriter()
.print("{\"returnMessage\":\"图片大小不能大于700K.\",\"returnCode\":\"1024\",\"imgUrl\":\"\"}");

}
} catch (Exception e) {
e.getStackTrace();
}
boolean isLegal = false;
for (String type : IMAGE_TYPE) {
if (StringUtils.endsWithIgnoreCase(item.getName(), type)) {
isLegal = true;
System.out.println(isLegal);
break;
}
System.out.println(isLegal);
}

try {
uuidName=generateRandonFileName(item.getName());
item.write(new File(newFile, uuidName));
item.delete();
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException();
}
}


String url = "http://image.brand.com"+ "/"+uuidName;
System.out.println(url);
response.getWriter().print(
"{\"returnMessage\":\"\",\"returnCode\":\"0000\",\"imgUrl\":\""
+ url + "\"}");

}


}catch (Exception e) {
e.getStackTrace();
}

}
public static String generateRandonFileName(String fileName) {
String ext = fileName.substring(fileName.lastIndexOf("."));
return UUID.randomUUID().toString() + ext;
}

}

转载于:https://www.cnblogs.com/zhaoblog/p/5360201.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值