有一个业务操作是:用户使用硬件在windows电脑产生了文件,需要上传到客户端,并且是在用户不操作的情况下。
思路是:在用户操作的jsp页面引入一个applet。这个applet是运行在客户端的java代码,是一个jar包,这样就可以把windows电脑上的文件随意操作了。将文件以流的形式传递到服务端,就可以上传到服务器了。
案例:将windows的图片上传到服务器上。
步骤:1.创建一个applet的jar。
2.引入到jsp页面
applet文件:创建一个Java project项目,直接创建一个class类
public class ImageSave extends Applet
{
private static final long serialVersionUID = 1L;
/**
* @param filePath widows文件的路径
* @param sinopath 服务器的项目发布地址
* @param djnm 单据id
* @param zznm 部门id
* @param djlx 单据的类型
* @param pzhj 拍照的备注
* @param photo_lb 拍照的类别(0,进门照片;1,称重照片)
* @return
* @throws IOException
*/
public String saveImage(String filePath, String sinopath, String djnm, String zznm, String djlx, String pzhj, String photo_lb)
throws IOException
{
File file = new File(filePath);
System.out.println("YZ图像保存>>file.exists():" + file.exists());
if ((!file.exists()) || (!file.isFile())) {
System.out.println("YZ图像保存,图片不存在");
return "-1";
}
//该路径为服务器的路径
String url = sinopath + "imageSaveCmd.cmd?method=imageSaveRm&djnm=" + djnm + "&zznm=" + zznm +
"&djlx=" + djlx + "&pzhj=" + pzhj + "&photo_lb=" + photo_lb + "&file=" + file;
System.out.println(url);
URL urlObj = new URL(url);
HttpURLConnection con = (HttpURLConnection)urlObj.openConnection();
con.setRequestMethod("POST");
con.setDoInput(true);
con.setDoOutput(true);
con.setUseCaches(false);
con.setRequestProperty("Connection", "Keep-Alive");
con.setRequestProperty("Charset", "UTF-8");
con.setRequestProperty("Content-Type", "multipart/form-data");
OutputStream out = new DataOutputStream(con.getOutputStream());
DataInputStream in = new DataInputStream(new FileInputStream(file));
System.out.println("YZ图片保存>>:" + in);
int bytes = 0;
byte[] bufferOut = new byte[1024];
while ((bytes = in.read(bufferOut)) != -1) {
out.write(bufferOut, 0, bytes);
}
System.out.println("YZ图像保存,存入图片.");
in.close();
out.flush();
out.close();
System.out.println("YZ图像保存,接受创建连接返回的图像保存状态前.");
BufferedInputStream inputStream = new BufferedInputStream(con.getInputStream());
int v = 0;
byte[] ret_bytes = new byte[1024];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while ((v = inputStream.read(ret_bytes)) > 0) {
baos.write(ret_bytes, 0, v);
}
System.out.println("YZ图像保存,接受创建连接返回的图像保存状态后.");
inputStream.close();
baos.close();
byte[] tmp = baos.toByteArray();
System.out.println("YZ图像保存,tmp长度>>:" + tmp.length);
String strRead = new String(tmp);
System.out.println("YZ图像保存,strRead值>>:" + strRead);
return strRead;
}
//删除图片
public void deleteImage(String imageName) {
try {
File file = new File(imageName);
if (file.exists()) {
boolean d = file.delete();
if (d)
System.out.println(">>>图片删除成功!");
else
System.out.println(">>>图片删除失败!");
}
}
catch (Exception e) {
System.out.println("-----删除图片异常!-----");
e.printStackTrace();
}
}
}
创建服务器处理文件:
public String imageSaveRm(HttpServletRequest req, HttpServletResponse rep, IErrorHandler errorHandler, IMessageHandler messageHandler,
ViewHelper viewHelper) {
String return_str = "imageSaveForward.success";
try {
int v = 0;
BufferedInputStream inputStream = new BufferedInputStream(req.getInputStream());
BspInfo bspInfo = (BspInfo) req.getSession().getAttribute("UserLoginInfo");
String lrrxm = bspInfo.getUserName();
String lrrnm = bspInfo.getUserId();
String cckdnm = "";
String djnm = req.getParameter("djnm");
String zznm = req.getParameter("zznm");
String djlx = req.getParameter("djlx");
String pzhj = req.getParameter("pzhj");
String photo_lb = req.getParameter("photo_lb");
String file = req.getParameter("file");
System.out.println("djnm="+djnm);
System.out.println("zznm="+zznm);
System.out.println("djlx="+djlx);
System.out.println("pzhj="+pzhj);
System.out.println("photo_lb="+photo_lb);
System.out.println("file="+file);
//由于windows路径是E:\\a\\b.jpg 这种格式的,只需要文件名称,故截取
int index=file.lastIndexOf("\\");
String names=file.substring((index+1),file.length());
System.out.println("文件名称names="+names+",index="+index);
List grszcckd=getCrkYktService().getGrszCckd(lrrxm,lrrnm);
if(grszcckd.size()>0){
HashMap mapgrszcckdcckdnm=(HashMap)grszcckd.get(0);
String cckdnmgrszcckd=mapgrszcckdcckdnm.get("CRK_GRSZ_CCKDNM").toString();
cckdnm=cckdnmgrszcckd;
}else {
cckdnm=zznm;
}
byte[] bytes = new byte[1024];
ByteArrayOutputStream baos = new ByteArrayOutputStream();
while ((v = inputStream.read(bytes)) > 0) {
baos.write(bytes, 0, v);
}
inputStream.close();
baos.close();
byte[] tmp = baos.toByteArray();
System.out.println(">>>>>tmp.length:" + tmp.length);
String name = file;//20160701文件名也去掉
System.out.println("name:"+name +" cckdnm: "+cckdnm );
String tplj = saveToServerRm(tmp,names,cckdnm,req);//将传来的流保存到服务器上
//将流保存到数据库中,根据个人需求,可以保存,可以不保存
getImageSaveDao().saveImage(tmp, zznm, djnm, djlx, pzhj, photo_lb,tplj,name);
}
catch (IOException e) {
System.out.println(e.getMessage());
return_str = "imageSaveForward.falture";
}
return return_str;
}
//将文件保存到服务器端
public String saveToServerRm(byte[] tmp ,String name,String cckdnm,HttpServletRequest req){
Calendar ctime = Calendar.getInstance();
SimpleDateFormat fymd = new SimpleDateFormat ("yyyyMMdd");
Date date = ctime.getTime();
String sDate = fymd.format(date);
System.out.println("sDate="+sDate);
System.out.println("sDate11="+sDate.substring(0, sDate.length()-2));
//如果文件不存在,则创建一个新文件
String path = req.getSession().getServletContext().getRealPath("/");
String pathServer=req.getContextPath()+"/upload/";//写入数据库的相对地址
System.out.println("pathServer="+pathServer);
String filePath = "";
if(path.indexOf("/")>-1){//服务器为liunx的创建目录
System.out.println("方法1");
filePath = path+"/upload";
System.out.println("linux path:"+filePath+"/"+name);
}else if(path.indexOf("\\")>-1){//服务器为windows的创建目录
System.out.println("方法2");
filePath = path +"\\upload";
System.out.println("windows path:"+filePath+"\\"+name);
}
FileOutputStream fos;
try {
File outfile = new File(filePath,name);
if (!outfile.exists()) {
outfile.getParentFile().mkdirs();
outfile.createNewFile();
System.out.println("创建文件夹");
} else{
System.out.println("文件夹已存在");
}
fos = new FileOutputStream(outfile);
fos.write(tmp);
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
System.out.println("FileNotFoundException异常");
e.printStackTrace();
} catch (IOException e) {
System.out.println("IOException异常");
// TODO Auto-generated catch block
e.printStackTrace();
}
return pathServer;
}
引入jsp页面:将applet文件打成jar。引入到jsp页面,放入body中即可。
<APPLET CODE="ImageSave.class"
ARCHIVE="<loushang:uipath/>jsp/genersoft/ecard/rkjs/imageSave_fat.jar"
name="ImageSaves"
height = "0"
width = "0"
hspace = "0"
vspace= "0">
</APPLET>
在js中调用这个applet
获取项目在服务器的路径:
String httpPath = "http://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath() + "/";
//前两个参数是项目中的,后几个参数,根据个人需要填充
document.all("ImageSaves").saveImage("D:\\a\\b.jpg",httpPath,"201907180030",cckdnm,"111","2","3");
通过以上的步骤就可以实现了。