您的位置:首页 > 编程语言 > Java开发

java笔记之WebProject(一)上传文件

2013-10-21 16:19 507 查看
1、8个必要的包,添加到WEB-INF/lib

commons-fileupload 组件下载:http://commons.apache.org/fileupload/

commons-io组件下载:http://commons.apache.org/io/

2、表单页面:

(1)enctype="multipart/form-data"

form的enctype属性为编码方式,常用有两种:application/x-www-form-urlencoded和multipart/form-data,默认为application/x-www-form-urlencoded。

action为get时候,浏览器用x-www-form-urlencoded的编码方式把form数据转换成一个字串(name1=value1&
amp;name2=value2...),然后把这个字串append到url后面,用?分割,加载这个新的url。
当action为post时候,浏览器把form数据封装到http body中,然后发送到server。
如果没有type=file的控件,用默认的application/x-www-form-urlencoded就可以了。

是如果有type=file的话,就要用到multipart/form-data了。浏览器会把整个表单以控件为单位分割,并为每个部分加上
Content-Disposition(form-data或者file),Content-Type(默认为text/plain),name(控件
name)等信息,并加上分割符(boundary)。

(2)注意type="file"

<form name="form5" method="post"  enctype="multipart/form-data"
action="<%=path%>/servlet/uploadFile">
Id:<input type="text" name="id" value="" /><br>
产品图片:<input type="file" name="file">
<input type="submit" value="上传" name="submit">
</form>


3、uploadFile.java核心代码:

(1)如果遇到:FileNotFoundException,可能是String upload_path = request.getRealPath("/upload");中的upload文件夹没有被在WebRoot文件夹创建

(2)上传之后不会在工程下的/webRoot/upload下看到文件,而是在real_path的路径

public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
request.setCharacterEncoding("utf-8");
//addProduct处理文件上传,并返回bool类型
boolean flag=addProduct(request, response);
out.print("上传结果"+flag);
out.flush();
out.close();
}

private boolean addProduct(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// 将表单中的文件类型提交
DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
// 构建一个文件上传类
ServletFileUpload servletFileUpload = new ServletFileUpload(
diskFileItemFactory);
// 设置单个上传文件的最大字节数:3M
servletFileUpload.setFileSizeMax(3 * 1024 * 1024);
// 总大小设置为6M
servletFileUpload.setSizeMax(6 * 1024 * 1024);
List<FileItem> list = null;
// 插入语句需要占位符
List<Object> params = new ArrayList<Object>();
// params.add(UUIDTools.getUUID());
String id = null;
try {
// 解析request的请求,list获取request的
list = servletFileUpload.parseRequest(request);
System.out.println(list.size());
// 取出所有表达的值,判断文本字段和非文本字段
for (FileItem fileItem : list) {
// 如果是文本字段
if (fileItem.isFormField()) {
System.out.println("不是文件");

// getFieldName取得表单中input的value值
if (fileItem.getFieldName().equals("id")) {

//取得当前字段的值,相当于一般情况下的String id = request.getParameter("id");
int id=fileItem.getString("utf-8");
System.out.println("id="+fileItem.getString("utf-8"));

} else {
System.out.println("是文件");
// 开始上传文件,本质还是IO流
try {
// 获得文件得名称
String image = fileItem.getName();
// 将文件名添加到占位符
params.add(image);
params.add(id);
// 获得工程下的upload文件夹的绝对路径,要注意可能要手动新建upload文件夹
@SuppressWarnings("deprecation")
String upload_path = request.getRealPath("/upload");
// 将路径包装起来
File real_path = new File(upload_path + "/"+image);
System.out.println("real_path--->>" + real_path);
// 将real_path写进去
fileItem.write(real_path);
// 把数据插入到数据库中
boolean flag = service.updatepicture(params);
System.out.println("数据库"+flag);
if (flag) {
return true;
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}


控制台输出信息:

real_path--->>/home/jl/Workspaces/MyEclipse 10/.metadata/.me_tcat/webapps/MyWebproject/upload/WebpageCaptureDemo.rar

4、上传之后的文件的链接如下:
http://192.168.1.108:8080/MyWebproject/upload/appwidget_collections.png
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: