0
点赞
收藏
分享

微信扫一扫

javaweb上传图片课堂代码笔记

minute_5 2022-01-08 阅读 26

TestUpload.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>上传图片</title>
</head>
<body>
<!-- http://127.0.0.1:8080/demo211229/test/test220104/TestUpload.jsp -->
 <form action="/demo211229/UploadServlet" method="post" enctype="multipart/form-data">
 	<input type="file" name="uploadFile1" /><br>
 	<input type="file" name="uploadFile2" /><br>
 	<input type="text" name="coad" /><br>
 	<input type="submit" value="上传" />

 </form>

</body>
</html>

UploadServlet.java

package test220104;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.UUID;

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

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;

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

	private static final long serialVersionUID = 1L;

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		System.out.println("uploadservlet-dopost");
		try {
			upload(req);
		} catch (FileUploadException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * 实现服务器端保存图片的功能
	 * 
	 * @throws FileUploadException
	 * @throws IOException 
	 */
	private void upload(HttpServletRequest req)
			throws FileUploadException, IOException {
		DiskFileItemFactory factory = new DiskFileItemFactory();
		ServletFileUpload uplaod = new ServletFileUpload(factory);
		List<FileItem> items = uplaod.parseRequest(req);
		for (FileItem item : items) {
			if (item.isFormField()) {// 是否是非文件域元素
				String name = item.getFieldName();// 得到参数名
				System.out.println("name=" + name);
				String value = item.getString();// 得到参数值
				value = new String(value.getBytes("ISO-8859-1"), "UTF-8");
				System.out.println("value=" + value);
			} else {// 文件域表单元素--保存文件
				//io流来拷贝图片的代码
				System.out.println(item.getFieldName() + " " + item.getName());// 参数名+参数值
				String fn=getFName(item);
				FileOutputStream fos = new FileOutputStream(getFPath()+"/"+fn);// 定义流,将流要写出的目标路径传入
				InputStream is = item.getInputStream();
				int length=-1;
				byte[] b=new byte[1024*1024];
				while(-1 != ( length=is.read(b)))
					fos.write(b,0,length);
				fos.flush();
				fos.close();
				is.close();
			}
		}
	}

	private String getFName(FileItem item) {// 获得唯一文件名,加上上传文件的扩展名
		String fn = item.getName();
		String uuid = UUID.randomUUID().toString();//得到随机唯一标识
		fn = uuid + fn.substring(fn.indexOf("."));// String提供的方法--要熟悉string的方法
		return fn;
	}

	private File getFPath() {// 得到保存上传来的文件的目录
		File f = new File("C:\\Users\\lxf99\\Desktop\\imgModel\\test");
		if (!f.exists())
			f.mkdir();
		return f;
	}
}
举报

相关推荐

0 条评论