关于文件上传这一块,我已经用了流,base64编码,表单(包含伪表单,处理客户端文件上传)的形式,可以说各有各的好处,但是本人更倾向于表单的形式提交,无论是处理网页的表单提交,还是客户端的伪表单提交都是一样的
首先第一种
一,流上传
/**
* savePath 保存路径
* file 文件
* saveFileName 采用何种文件命名
* **/
public String file(String savePath, MultipartFile file)
throws IOException {
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(1024 * 1024 * 5);
// 文件保存地址
java.io.File temDirectory = new java.io.File(savePath);
factory.setRepository(temDirectory);
/**
* // ServletFileUpload upload = new ServletFileUpload(factory);
* //设置文件上传大小 upload.setSizeMax(1024 * 1024 * 5);
*/
FileItem items = ((CommonsMultipartFile) file).getFileItem();
// List items = upload.parseRequest(request);
System.out.println("items" + items);
String filedName = null;
String fileName = null;
String NewFilenName = null;
// 遍历item
// 若是一个一般的表单域
if (items.isFormField()) {
String name = items.getFieldName();
String value = items.getString();
System.out.println(name + ":" + value);
} else { // 若是文件域则把文件保存到文件夹下
System.out.println("进来了");
filedName = items.getFieldName();
fileName = items.getName();
// 获取文件后缀
int cut = fileName.lastIndexOf(".");
String newCutString = fileName.substring(cut);
System.out.println("newCutString=" + newCutString);
// 新文件名
fileName = new Date().getTime() + RandomUtil.generateNumber2()
+ newCutString;
String contentype = items.getContentType();
long sizeInBytes = items.getSize();
System.out.println("filedName=" + filedName);
System.out.println("fileName=" + fileName);
System.out.println("contentype=" + contentype);
System.out.println("sizeInBytes=" + sizeInBytes);
InputStream in = items.getInputStream();
byte[] buffer = new byte[1024];
int len = 0;
fileName = savePath + fileName;
System.out.println("2fileName=" + fileName);
OutputStream out = new FileOutputStream(fileName);
while ((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
out.close();
in.close();
}
return fileName;
}
二,多图流式上传
/**
* savePath 保存路径 file 文件 saveFileName 采用何种文件命名
* **/
public String ManayPic(HttpServletRequest request, String savePath)
throws Exception {
System.out.println("文件传送");
System.out.println("savePath" + savePath);
// 一
DiskFileItemFactory factory = new DiskFileItemFactory();
factory.setSizeThreshold(1024 * 1024 * 5);
// 文件保存地址
java.io.File temDirectory = new java.io.File(savePath);
factory.setRepository(temDirectory);
// 上传处理工具类(高水平API上传处理?)
ServletFileUpload upload = new ServletFileUpload(factory);
/**
* // ServletFileUpload upload = new ServletFileUpload(factory);
* //设置文件上传大小 upload.setSizeMax(1024 * 1024 * 5);
*/
// FileItem items = ((CommonsMultipartFile) file).getFileItem();
List items = (List) upload
.parseRequest(new ServletRequestContext(request));
;
System.out.println("items" + items);
String filedName = null;
String fileName = null;
String NewFilenName = null;
// 遍历item
for (FileItem item : items) {
filedName = item.getFieldName();
fileName = item.getName();
// 获取文件后缀
int cut = fileName.lastIndexOf(".");
String newCutString = fileName.substring(cut);
System.out.println("newCutString=" + newCutString);
// 新文件名
fileName = new Date().getTime() + RandomUtil.generateNumber2()
+ newCutString;
String contentype = item.getContentType();
long sizeInBytes = item.getSize();
InputStream in = item.getInputStream();
byte[] buffer = new byte[1024];
int len = 0;
fileName = savePath + fileName;
System.out.println("2fileName=" + fileName);
OutputStream out = new FileOutputStream(fileName);
while ((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
}
out.close();
in.close();
}
// }
return fileName;
}
三,上传文件之直接写入
public String uploadIcon(MultipartFile pic,// 接收文件
String savePath// 保存路径
) throws Exception {
// 原始名称
String originalFilename = pic.getOriginalFilename();
String fileName = null;
// 上传图片
if (pic != null && originalFilename != null
&& originalFilename.length() > 0) {
// 存储图片的物理路径
// String pic_path = "C:\\Users\\Administrator\\Desktop\\上传文件\\";
// String pic_path = "/mnt/images/replies/";
// 新的图片名称
String newFileName = UUID.randomUUID()
+ originalFilename.substring(originalFilename
.lastIndexOf("."));
// 新图片
File newFile = new File(savePath + newFileName);
// 将内存中的数据写入磁盘
pic.transferTo(newFile);
fileName = newFileName;
System.out.println(fileName);
}
return fileName;
}
四,base64编码图片上传(数字7代表最大上传的图片格式,提示:多张图片用逗号隔开上传)
/**
* 多张图片路径添加
*
* @param request
* @param id
* @param Imgpath
* 图片路径 图片格式为xxx.jpg,xxx.jpg,xxx.jpg
* @param filename
* 文件名自定义
* @return
* @throws Exception
*/
public String manyImgPathAdd(HttpServletRequest request, String userId,String filename,
String Imgpath) throws Exception {
String cutnew = "";
String cut = "";
String pathPicture = request.getSession().getServletContext()
.getRealPath("");
LzhUtils.createFolder(pathPicture +"/" +filename);
String[] covers = Imgpath.split(",");
String urlList = new String();
System.out.println(covers.length);
for (int i = 0; i < covers.length; i++) {
String newPicturePath = pathPicture +"/"+filename + "/" + userId
+ RandomUtil.generateNumber2() + ".jpg";
System.out.println(covers[i].toString());
LzhUtils.base64Decode(covers[i], newPicturePath);
if (i < 7) {
urlList = newPicturePath;
} else {
urlList = urlList + "," + newPicturePath;
}
cut = urlList.substring(urlList.indexOf("xuanmei")) + "," + cut;
System.out.println("cut1:" + cut);
}
cut.split(",");
cutnew = cut.substring(0, cut.length() - 1);
System.out.println("拼接之后的照片截取" + cutnew);
return cutnew;
}
五,伪表单上传
作为服务端,处理表单和伪表单都是差不多的,但是区别还是有一点点
public String upload(Model model,HttpServletRequest request,MultipartRequest multipartRequest)throws Exception{
//获取项目录取
String webpath = request.getSession().getServletContext().getRealPath("");
String uploadpath = webpath+"/NurseImg/ReportImg/";//上传路径
String fileName = null;
List<MultipartFile> pic = multipartRequest.getFiles("pics");
String picth = "";
String newpath = "";
for (int i = 0; i < pic.size(); i++) {
String originalFilename = pic.get(i).getOriginalFilename();
System.out.println("originalFilename="+originalFilename);
if(null == originalFilename || "".equals(originalFilename)){
continue;
}
// 新的图片名称
String newFileName =RandomUtil.generateNumber2()
+ originalFilename.substring(originalFilename
.lastIndexOf("."));
// 新图片
java.io.File newFile = new java.io.File(uploadpath + newFileName);
fileName = newFileName;
newpath = "NurseImg/ReportImg/"+fileName;
System.out.println("newFile="+newFile);
// 将内存中的数据写入磁盘
pic.get(i).transferTo(newFile);
if (i == 0) {
picth = newpath;
} else {
picth = picth + "," + newpath;
}
}
return picth;
}
可以看到,客户端远程请求我们定义了一个MultipartRequest参数,通过这个根据客户端定义传递文件的参数就可以拿到客户端请求的文件了
其实上面几种方法可以交互使用,但是合适的场景使用合适的方法才是最好的方法.大牛勿喷