java后台 app端图片上传


单一图片上传


if (!file.isEmpty()) {
					String[] str = file.getContentType().split("/");
					String path = request.getSession().getServletContext()
							.getRealPath("portrait");
					String fileName = new Date().getTime() + "." + str[1];
					File targetFile = new File(path, fileName);
					if (!targetFile.exists()) {
						targetFile.mkdirs();
					}
					try {
						file.transferTo(targetFile);// 保存文件
					} catch (Exception e) {
						e.printStackTrace();
					}
					String basePath = request.getScheme() + "://"
							+ request.getServerName() + ":"
							+ request.getServerPort()
							+ request.getContextPath() + "/";//获取的服务器地址
					uss.setUs_img(basePath + "portrait/" + fileName);
				}



单图片修改

if (!file.isEmpty()) {
					String[] str = file.getContentType().split("/");
					String path = request.getSession().getServletContext()
							.getRealPath("portrait");
					String fileName = new Date().getTime() + "." + str[1];
					File targetFile = new File(path, fileName);
					if (!targetFile.exists()) {
						targetFile.mkdirs();
					}
					try {
						file.transferTo(targetFile);// 保存文件
					} catch (Exception e) {
						e.printStackTrace();
					}


					String basePath = request.getScheme() + "://"
							+ request.getServerName() + ":"
							+ request.getServerPort()
							+ request.getContextPath() + "/";
					System.out.println(basePath + "+++++++");
					// E:\Tomcat 6.0\webapps\ho\ upload\sasad.jpg
					String img2 = uss.getUs_img();
					System.out.println(img2 + "---------");
					String path1 = request.getServletContext().getRealPath("")
							+ img2.substring(img2.indexOf("ZZcar/") + 5);//截取数据库中存储的地址1信息
					System.out.println(path1);
					File fif = new File(path1);
					if (fif.exists()) {
						fif.delete();
					}


					uss.setUs_img(basePath + "portrait/" + fileName);
				}



多图片上传

for (int i = 0; i < neirong.length; i++) {
			if (!file1[i].isEmpty()) {

				String path = request.getSession().getServletContext()
						.getRealPath("carnews");
				String[] str = file1[i].getContentType().split("/");
				String path1 = request.getSession().getServletContext()
						.getRealPath("carnews");
				String fileName = new Date().getTime() + i + "." + str[1];
				File targetFile = new File(path1, fileName);
				if (!targetFile.exists()) {
					targetFile.mkdirs();
				}
				try {
					InetAddress addr = InetAddress.getLocalHost();
					file1[i].transferTo(targetFile);// 保存文件
					String basePath = request.getScheme() + "://"
							+ addr.getHostAddress().toString() + ":"
							+ request.getServerPort()
							+ request.getContextPath() + "/";

					cc.setCn_img(basePath + "carnews/" + fileName);

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

			} else {
				cc.setCn_img("");
			}
		}





你可能感兴趣的:(java,图片上传)