Sevelt 代码如下
package com.ray;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Upload extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String fraternityLogo = new String(request.getParameter("fLogo").getBytes("ISO-8859-1"),"utf-8");
String fraternityName = new String(request.getParameter("fName").getBytes("ISO-8859-1"),"utf-8");
String tempPath = "";// 图片在系统中的路径
String url = "";
if (!fraternityLogo.equals("")) {
File file = new File(fraternityLogo);
// 取得文件名及后缀!!
String tupName = file.getName();
String fileName = tupName.substring(0, tupName.indexOf("."));
String fileEnd = tupName.substring(tupName.indexOf(".") + 1,
tupName.length());
if (fileEnd.equals("jpg") || fileEnd.equals("JPG")
|| fileEnd.equals("gif") || fileEnd.equals("GIF")) {
// web 图片路径文件夹路径
String webpath = getServletContext().getRealPath("/") + "img\\"
+ fraternityName + "." + fileEnd;
tempPath = fraternityName + "." + fileEnd;
FileInputStream inStream = new FileInputStream(file);
byte[] b = new byte[(int) file.length()];
FileOutputStream fos = new FileOutputStream(webpath);
int n;
while ((n = inStream.read(b)) != -1) {
fos.write(b, 0, n);
}
fos.flush();// 写到磁盘上
fos.close();// 关闭文件流
}
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request,response);
}
}
jsp代码
<body>
<h3 align="center">servlet+jap 实现图片上传</h3>
<form action="upload.do" method="post">
文件名称:<input type="text" name="fName"><br>
<input type="file" name="fLogo"/>
<input type="submit" value="上传"/>
</form>
</body>