采用流的形式存储图片进行上传图片

来源:互联网 发布:抢票软件演唱会 编辑:程序博客网 时间:2024/05/18 19:45


// 上传图片
@RequestMapping("/upload")

public void upload(@RequestParam(value="file",required=false)MultipartFile file,HttpServletRequest request,ModelMap model, HttpServletResponse response,String id) throws IOException, SQLException{
Criteria ca = new Criteria("id", id);
log.info("开始上传机构图片");
Organization org = organizationService.getOrganization(ca);
org.setUpdatetime(new Date());
String newFileName =null;
String exe =null;

String path = request.getSession().getServletContext().getRealPath("/resources/images/upload");
Map<String, Object> map = new HashMap<String, Object>();
if(file.getOriginalFilename().length()==0){
MessageUtils.outputJSONResult("fail",response);
return;
}
else if(file!=null){
String fileName=file.getOriginalFilename();
exe = FilenameUtils.getExtension(fileName);
newFileName = UUID.randomUUID().toString();

File targetFile=new File(path+"\\"+newFileName+"."+exe);


if(!targetFile.exists()){
targetFile.mkdirs();
}
try {
file.transferTo(targetFile);
} catch (Exception  e) {

e.printStackTrace();
log.error("上传失败");
}
log.info("上传路径和文件名"+request.getContextPath()+"/images/upload/"+fileName);
model.addAttribute("fileUrl", request.getContextPath()+"/images/upload/"+fileName+".jsp");
//request.getSession().setAttribute("fileName",request.getContextPath()+"/images/upload/"+newFileName+"."+exe);
map.put("fileUrl", request.getContextPath()+"/images/upload/"+newFileName+"."+exe);

}
String url = ConfigurationHelper.getDbUrl();
String userName = ConfigurationHelper.getUserName();
String password = ConfigurationHelper.getPassword();
Connection conn=null;
PreparedStatement statement = null;
try {
conn = DriverManager.getConnection(url, userName, password);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
log.error("数据库连接失败");
}
if(request.getParameter("s")!=null){
String sql="update organization set THUMBNAIL=? where id="+id;
statement = conn.prepareStatement(sql);
statement.setBlob(1, new FileInputStream(path+"\\"+newFileName+"."+exe));
model.addAttribute("log", "thumbnail");
}else{
String sql="update organization set PICTURE=? where id="+id;
statement = conn.prepareStatement(sql);
statement.setBlob(1, new FileInputStream(path+"\\"+newFileName+"."+exe));
model.addAttribute("log", "pic");
}

statement.executeUpdate();
statement.close();
//deleteFile(path);
MessageUtils.outputJSONResult("success",response);

//return "organization.upload";
}
0 0
原创粉丝点击