选择图片点击上传后出现
HTTP Status 404 - /image/UploadPict
type Status report
message /image/UploadPict
description The requested resource (/image/UploadPict) is not available.
Apache Tomcat/6.0.13
package image;
import java.io.File;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;
public class UploadPict extends HttpServlet{
protected void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
String id =request.getParameter("imgid");
System.out.println("ID="+id);
//上传图片保存路径
String filePath=getServletContext().getRealPath("/")+"imgs";
File file=new File(filePath);
if(!file.exists()){//如果不存在这个路径
file.mkdirs();//就创建
}
SmartUpload su = new SmartUpload();//上传图片的工具类
su.initialize(getServletConfig(), request, response);// 初始化
try {
su.upload();// 上传
com.jspsmart.upload.File f1 = su.getFiles().getFile(0);//因为只一次只上传一个图片,所以就getFile(0),如果多次还要迭代遍历
String imageName = f1.getFileName();//得到图片的名字
int idx = imageName.lastIndexOf(".");
String imageType = imageName.substring(idx, imageName.length());// 得到图片的类型,比如是 .jpg
String newImageName = String.valueOf(System.currentTimeMillis());//图片的新名字,最好不要用随机数,因为随机数也可能有一样的
String path = "E:"+File.separator+"image"+File.separator+File.separator+File.separator+File.separator;
String imagePath = path+File.separator+newImageName+imageType;//已经保存的图片的绝对路径,下面要对图片重新命名
//生成保存图片的路径,File.separator是个跨平台的分隔符
f1.saveAs(imagePath);// 保存图片到这个目录下
} catch (SmartUploadException e) {
e.printStackTrace();
}
}
}
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
浏览图片
请选择上传的图片: <input type="file" name="imgid" id="imgid" value="选择图片">