用户注册



邮箱:

密码:

用户登录


邮箱:

密码:
记住登录一个月忘记密码?

发表随想


还能输入:200字
云代码 - java代码库

图片上传

2013-08-22 作者: wcj举报

[java]代码库

-----------------------------jsp页面--------------------------------------------------------------
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>上传文件</title>
</head>
<body>
	<form action="FileUpload" method="post" enctype="MULTIPART/FORM-DATA">
		参数:<input type="text" name="para1" /><br>
		上传文件:<input type="file" name="aa" /><br>
		另选文件:<input type="file" name="bb" /><br>
		再选文件:<input type="file" name="cc" /><br>
		<input type="submit" value="提交" />
	</form>
</body>
</html>
-----------------------------后台serverlet--------------------------------------------------------------

package com.cheletong.servlet;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Random;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * Servlet implementation class MaterialManage
 */

@WebServlet("/FileUpload")
public class FileUpload extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	/**
	 * @throws IOException
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		JSONObject resultJson = new JSONObject();
		JSONArray paths = new JSONArray();
		Random ran = new Random();
		int respCode = -1;
		try {
			request.setCharacterEncoding("utf-8");
			response.setContentType("text/html;charset=utf-8");

			String uploadPath = getServletContext().getRealPath("/upload");
			System.out.println(uploadPath);
			String tempPath = uploadPath + "\\temp";
			String today = new SimpleDateFormat("yyyyMMdd").format(new Date());
			String todayPath = uploadPath + "\\" + today;

			if (uploadPath == null) {
				return;
			}

			File uploadDir = new File(uploadPath);
			File tempDir = new File(tempPath);
			File todayDir = new File(todayPath);

			if (!uploadDir.exists()) {
				uploadDir.mkdir();
			}
			if (!tempDir.exists()) {
				tempDir.mkdir();
			}
			if (!todayDir.exists()) {
				todayDir.mkdir();
			}

			if (!ServletFileUpload.isMultipartContent(request)) {
				return;
			}

			DiskFileItemFactory factory = new DiskFileItemFactory();
			factory.setRepository(tempDir);
			factory.setSizeThreshold(1024 * 1024 * 1);

			ServletFileUpload sfu = new ServletFileUpload(factory);
			sfu.setHeaderEncoding("utf-8");

			List<FileItem> fileItems = null;
			try {
				fileItems = sfu.parseRequest(request);
			} catch (FileUploadException e) {
				e.printStackTrace();
				return;
			}
			int i;
			for (i = 0; i < fileItems.size(); i++) {
				FileItem item = fileItems.get(i);
				if (!item.isFormField()) {
					String itemFullName = item.getName();
					if (itemFullName.length() > 0) {
						String fileExtension = itemFullName
								.substring(itemFullName.lastIndexOf("."));
						String fileNewName = new SimpleDateFormat(
								"yyyyMMdd_HHmmss").format(new Date())
								+ "_"
								+ Math.abs(ran.nextInt()) + fileExtension;

						File file = new File(todayPath, fileNewName);
						try {
							item.write(file);
							String name = "/upload/" + today + "/"
									+ file.getName();							
							JSONObject path = new JSONObject();
							path.put("Path", name);
							paths.add(path);
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
				}
			}
			if(i == fileItems.size()) {
				respCode = 0;
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			PrintWriter pw = response.getWriter();
			resultJson.put("response", respCode);
			resultJson.put("data", paths);
			pw.write(resultJson.toString());
			pw.flush();
			pw.close();
		}
	}

	/**
	 * @throws IOException
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		doPost(request, response);
	}

}


网友评论    (发表评论)

共5 条评论 1/1页

发表评论:

评论须知:

  • 1、评论每次加2分,每天上限为30;
  • 2、请文明用语,共同创建干净的技术交流环境;
  • 3、若被发现提交非法信息,评论将会被删除,并且给予扣分处理,严重者给予封号处理;
  • 4、请勿发布广告信息或其他无关评论,否则将会删除评论并扣分,严重者给予封号处理。


扫码下载

加载中,请稍后...

输入口令后可复制整站源码

加载中,请稍后...