jsp实习的文件上传案例
文件上传需要用到:common-fileupload和common-io这两个jar包。
客户端代码:- <form action="<%=path %>/servlet/UploadFileService" method="post" enctype="multipart/form-data">
- 文件:<input type="file" name="file"><br />
- <input type="submit" value="上传">
-
- </form>
复制代码 服务端代码:- request.setCharacterEncoding("utf-8");
- response.setCharacterEncoding("utf-8");
- response.setContentType("text/html;charset=utf-8");
-
- //1.判断文件上传的是否没有子文件
- boolean isMultipart = ServletFileUpload.isMultipartContent(request);
- if(isMultipart) {
- // 2得到存放文件的真实路径
- String realpath = request.getSession().getServletContext().getRealPath("/files");
- System.out.println(realpath);
- File dir = new File(realpath);
- if(!dir.exists()) {
- dir.mkdirs();
- }
-
- FileItemFactory factory = new DiskFileItemFactory();
- ServletFileUpload upload = new ServletFileUpload(factory);
- upload.setHeaderEncoding("utf-8");
- try {
- List<FileItem> items = upload.parseRequest(request);
- for(FileItem item : items) {
- if(item.isFormField()) {
- String name = item.getFieldName();
- String value = item.getString("utf-8");
- System.out.println(name + "=" + value);
- }
- else {
- item.write(new File(dir,item.getName().toString()));
- }
- }
- } catch (Exception e) {
- // TODO Auto-generated catch bloc
- e.printStackTrace();
- }
-
- } else {
- System.out.println("该文件不能上传");
- }
复制代码 |
|