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

Posted xue123

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了一个图片上传的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;
}

}

以上是关于一个图片上传的servlet,传到本地磁盘,要传到服务器请修改的主要内容,如果未能解决你的问题,请参考以下文章

如何将 Azure VM 磁盘直接上传到 Blob 存储?

将图像从库中上传到服务器

【贴吧上传图片画质】电脑传到贴吧图片,体积和画质都下降的很厉害,但看到有些人就很清晰,不知道有啥

vue 上传图片时 base64 怎么传到java后台

怎样把自己的照片传到百度网上

thinkphp 传到服务器报错1146