java 上传图片同时获得图片的宽和高
程序员文章站
2022-05-25 21:47:38
...
public ActionForward upload(ActionMapping mapping, ActionForm form, HttpServletRequest request,
HttpServletResponse response) throws IOException {
FileForm fileForm = (FileForm) form;
FormFile file1 = fileForm.getFile1();
HashMap<String, Object> jsonMap = new HashMap<String, Object>();
boolean success = false;
String message = "";
String fileURL = "";
int width = 0;
int height = 0;
if (file1 != null) {
//上传路径
String dir = request.getSession(true).getServletContext().getRealPath("/uploadFile");
OutputStream fos = null;
try {
// 获得文件后缀
String type = file1.getFileName().substring(file1.getFileName().lastIndexOf("."),
file1.getFileName().length());
BufferedImage bi = ImageIO.read(file1.getInputStream());
// System.out.println("Width=" + bi.getWidth());
// System.out.println("Height=" + bi.getHeight());
width = bi.getWidth();
height = bi.getHeight();
// 获取当前时间
Calendar c = Calendar.getInstance();
c.setTime(new Date());
String time = "" + c.get(c.YEAR) + (c.get(c.MONTH) + 1) + c.get(c.DATE) + c.get(c.HOUR_OF_DAY)
+ c.get(c.MINUTE) + c.get(c.SECOND);
String newname = time + type;
fileURL = "uploadFile/" + newname;
fos = new FileOutputStream(dir + "/" + newname);
fos.write(file1.getFileData(), 0, file1.getFileSize());
fos.flush();
success = true;
message = "图片上传成功";
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
success = false;
message = "图片上传失败";
} finally {
try {
fos.close();
} catch (Exception e) {
success = false;
message = "图片上传失败";
}
}
}
jsonMap.put("success", success);
jsonMap.put("message", message);
jsonMap.put("fileURL", fileURL);
jsonMap.put("width", width);
jsonMap.put("height", height);
String json = Convert.mapTojson(jsonMap).toString();
// 设置响应内容格式
response.setContentType("text/html;charset=utf-8");
// 获取流
PrintWriter out = response.getWriter();
// 将数据以json格式打到客户端
out.print(json);
// 清空缓存
out.flush();
// 关闭流
out.close();
//页面跳转
return null;
}
主要利用BufferedImage类获取图片的高度和宽度 上一篇: css图片不显示
推荐阅读