物料之图片上传
来源:互联网 发布:新网域名备案 编辑:程序博客网 时间:2024/05/03 14:35
form的method一定要post,还有就是enctype="multipart/form-data";
默认的是"application/x-www-form-urlencoded",此时在servlet中是无法用req.getParameter()得到表单参数的,必须要用fileupload组件里面的工具来取得,FileItem对象可以取得.item.getString()取得.
上传物料图片的第一种方案:
采用图片名称和物料代码一样的名称.如物料代码为a0001,则图片名为a0001.gif.
路径的问题:路径名是什么呢?有几种方式
1.用sys-config.xml进行配置,然后读取
2.在web.xml中进行配置路径名,然后在servlet中进行读取
3.动态创建,在自己的web应用下面创建,没有就创建,有就可以拿到.在servlet的初始化中进行创建,
上传物料的第二种方案:
将图片名存放到数据库里面去,物料表中就要有一个存放图片名称的字段.
实现方式一:(代码)
public class FileUploadServlet extends AbstractItemServlet {
private String tempFileStr;
private String uploadFileStr;
@Override
public void init() throws ServletException {
tempFileStr=this.getServletContext().getRealPath("ImagesUploadTemp");
uploadFileStr=this.getServletContext().getRealPath("ImagesUploaded");
File fileTemp=new File(tempFileStr);
File fileUpload=new File(uploadFileStr);
if(!fileTemp.exists()){
fileTemp.mkdir();
}
if(!fileUpload.exists()){
fileUpload.mkdir();
}
super.init();
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
upload(request,response);
}
private void upload(HttpServletRequest request,HttpServletResponse response )
throws ServletException, IOException{
String itemNum="";
final long MAX_SIZE = 3 * 1024 * 1024;// 设置上传文件最大为 3M
// 允许上传的文件格式的列表
final String[] allowedExt = new String[] { "jpg", "jpeg", "gif", "txt",
"doc", "docx", "mp3", "wma", "m4a" };
response.setContentType("text/html");
// 设置字符编码为UTF-8, 这样支持汉字显示
response.setCharacterEncoding("UTF-8");
// 实例化一个硬盘文件工厂,用来配置上传组件ServletFileUpload
DiskFileItemFactory dfif = new DiskFileItemFactory();
dfif.setSizeThreshold(4096);// 设置上传文件时用于临时存放文件的内存大小,这里是4K.多于的部分将临时存在硬盘
dfif.setRepository(new File(tempFileStr));// 设置存放临时文件的目录,web根目录下的ImagesUploadTemp目录
// 用以上工厂实例化上传组件
ServletFileUpload sfu = new ServletFileUpload(dfif);
// 设置最大上传尺寸
sfu.setSizeMax(MAX_SIZE);
PrintWriter out = response.getWriter();
// 从request得到 所有 上传域的列表
List fileList = null;
try {
fileList = sfu.parseRequest(request);
} catch (FileUploadException e) {// 处理文件尺寸过大异常
if (e instanceof SizeLimitExceededException) {
out.println("文件尺寸超过规定大小:" + MAX_SIZE + "字节<p />");
out.println("<a href=\"javascript:history.go(-1)\" target=\"_self\">返回</a>");
return;
}
e.printStackTrace();
}
// 没有文件上传
if (fileList == null || fileList.size() == 0) {
out.println("请选择上传文件<p />");
out.println("<a href=\"javascript:history.go(-1)\" target=\"_self\">返回</a>");
return;
}
// 得到所有上传的文件
Iterator fileItr = fileList.iterator();
// 循环处理所有文件
while (fileItr.hasNext()) {
FileItem fileItem = null;
String path = null;
long size = 0;
// 得到当前文件
fileItem = (FileItem) fileItr.next();
// 忽略简单form字段而不是上传域的文件域(<input type="text" />等)
if (fileItem == null || fileItem.isFormField()) {
itemNum=fileItem.getString();
continue;
}
// 得到文件的完整路径
path = fileItem.getName();
// 得到文件的大小
size = fileItem.getSize();
if ("".equals(path) || size == 0) {
out.println("请选择上传文件<p />");
out.println("<a href=\"javascript:history.go(-1)\" target=\"_self\">返回</a>");
return;
}
// 得到去除路径的文件名
String t_name = path.substring(path.lastIndexOf("\\") + 1);
// 得到文件的扩展名(无扩展名时将得到全名)
String t_ext = t_name.substring(t_name.lastIndexOf(".") + 1);
// 拒绝接受规定文件格式之外的文件类型
int allowFlag = 0;
int allowedExtCount = allowedExt.length;
for (; allowFlag < allowedExtCount; allowFlag++) {
if (allowedExt[allowFlag].equals(t_ext))
break;
}
if (allowFlag == allowedExtCount) {
out.println("请上传以下类型的文件<p />");
for (allowFlag = 0; allowFlag < allowedExtCount; allowFlag++)
out.println("*." + allowedExt[allowFlag]
+ " ");
out.println("<p /><a href=\"javascript:history.go(-1)\" target=\"_self\">返回</a>");
return;
}
long now = System.currentTimeMillis();
// 根据系统时间生成上传后保存的文件名
String prefix = String.valueOf(now);
// 保存的最终文件完整路径,保存在web根目录下的ImagesUploaded目录下
String u_name = uploadFileStr+"/"
+ prefix + "." + t_ext;
try {
// 保存文件
fileItem.write(new File(u_name));
itemManager.uploadImage(itemNum, prefix + "." + t_ext);
out.println("文件上传成功. 已保存为: " + prefix + "." + t_ext
+ " 文件大小: " + size + "字节<p />");
out.println("<a href=\"javascript:history.go(-1)\" target=\"_self\">继续上传</a>");
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
实现的代码二:
public class FileUploadServlet extends AbstractItemServlet {
private File uploadPath;
private File tempPath;
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
//form提交采用multipart/form-data,无法采用req.getParameter()取得数据
//String itemNo = req.getParameter("itemNo");
//System.out.println("itemNo======" + itemNo);
DiskFileItemFactory factory = new DiskFileItemFactory();
// maximum size that will be stored in memory
factory.setSizeThreshold(4096);
// the location for saving data that is larger than getSizeThreshold()
factory.setRepository(tempPath);
ServletFileUpload upload = new ServletFileUpload(factory);
// maximum size before a FileUploadException will be thrown
upload.setSizeMax(1000000 * 20);
try {
List fileItems = upload.parseRequest(req);
String itemNo = "";
for (Iterator iter = fileItems.iterator(); iter.hasNext();) {
FileItem item = (FileItem) iter.next();
//是普通的表单输入域
if(item.isFormField()) {
if ("itemNo".equals(item.getFieldName())) {
itemNo = item.getString();
}
}
//是否为input="type"输入域
if (!item.isFormField()) {
String fileName = item.getName();
long size = item.getSize();
if ((fileName == null || fileName.equals("")) && size == 0) {
continue;
}
//截取字符串 如:C:\WINDOWS\Debug\PASSWD.LOG
fileName = fileName.substring(fileName.lastIndexOf("\\") + 1, fileName.length());
item.write(new File(uploadPath, fileName));
itemManager.uploadItemImage(itemNo, fileName);
}
}
res.sendRedirect(req.getContextPath() + "/servlet/item/SearchItemServlet");
} catch (Exception e) {
e.printStackTrace();
throw new ApplicationException("上传失败!");
}
}
public void init() throws ServletException {
uploadPath = new File(getServletContext().getRealPath("upload"));
System.out.println("uploadPath=====" + uploadPath);
//如果目录不存在
if (!uploadPath.exists()) {
//创建目录
uploadPath.mkdir();
}
//临时目录
tempPath = new File(getServletContext().getRealPath("temp"));
if (!tempPath.exists()) {
tempPath.mkdir();
}
//显示调用父类的init方法
super.init();
}
}
- 物料之图片上传
- 上传图片之上传前预览图片
- 上传图片之全过程
- 图片上传之压缩
- IOS之上传图片
- 图片上传之压缩
- 图片上传之压缩
- iOS 之图片上传
- 图片上传之fileupload
- 图片上传之fileupload
- springmvc之上传图片
- 《ReactNative》之图片上传
- TP5之图片上传
- PHP之图片上传
- 图片上传_ajax上传之改进版本
- JAVA附件上传之图片上传
- 图片上传之uploadify插件上传
- 单文件上传之上传图片
- 关于Android的一些设计(二)
- 你每天花了多少时间与你的孩子交流!
- jdbc结果集rs null .next()
- 也谈创业
- Linux下./configure错误详解
- 物料之图片上传
- checking for C++ compiler default output file name... configure: error: C++
- SRM 512 div2 512point
- Java线程:新特征-线程池
- Chorme书签无法同步的解决办法
- Linux命令行下全路径显示
- reverse proxy配置中的路径转换问题
- wince 休眠 唤醒
- memcached完全剖析.memcached的基础