1.上传
package com.gx.servlet;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 文件上传
* @date 2015-8-10 下午5:59:47
*/
public class Upload extends HttpServlet{
private static final long serialVersionUID = 5963104239031957110L;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//设置响应编码
request.setCharacterEncoding("gbk");
response.setContentType("text/html; charset=gbk");
InputStream inputStream = request.getInputStream();
PrintWriter out = response.getWriter();
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
int bLen = 0;
byte[] buffer = new byte[1024 * 8];
while ((bLen = inputStream.read(buffer)) > 0) {
baos.write(buffer, 0, bLen);
}
String filePath = ""; // 文件上传路径
String fileName = ""; // 文件名称
String fileLength = ""; // 文件长度
try {
filePath = new String(request.getHeader("FilePath").getBytes("ISO-8859-1"),"gbk");
fileName = new String(request.getHeader("FileName").getBytes("ISO-8859-1"),"gbk");
fileLength = new String(request.getHeader("FileLength").getBytes("ISO-8859-1"),"gbk");
System.out.println(new String(request.getHeader("FilePath").getBytes("ISO-8859-1"),"gbk"));
System.out.println(new String(request.getHeader("FileName").getBytes("ISO-8859-1"),"gbk"));
System.out.println(new String(request.getHeader("FileLength").getBytes("ISO-8859-1"),"gbk"));
System.out.println(request.getSession().getServletContext().getRealPath("/WebRoot/upload"));
} catch (Exception e) {
e.printStackTrace();
}
/*File file = new File(request.getSession().getServletContext().getRealPath("/upload"),
new String(request.getHeader("FileName").getBytes("ISO-8859-1"),"gbk"));*/
File file = new File("D:/servletUpload/",
new String(request.getHeader("FileName").getBytes("ISO-8859-1"),"gbk"));
file.mkdirs();
if(file.exists()){
file.delete();
}
file.createNewFile();
FileOutputStream outPut = new FileOutputStream(file);
outPut.write(baos.toByteArray());
outPut.flush();
outPut.close();
//响应输出
out.println("1:成功"); // 成功
} catch (Exception e) {
out.println("0:失败"); // 失败
e.printStackTrace();
}
}
}
2.下载
package com.gx.servlet;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 文件下载
* @date 2015-8-11 上午10:07:55
*/
public class Download extends HttpServlet {
private static final long serialVersionUID = -1217157202858492834L;
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
this.doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.setCharacterEncoding("gbk");
response.setContentType("text/html; charset=gbk");
String fileName = ""; // 下载文件名称
try {
fileName = new String(request.getHeader("FileName").getBytes("ISO-8859-1"),"gbk");
} catch (Exception e) {
fileName = new String(request.getParameter("FileName").getBytes("ISO-8859-1"),"gbk");
}
System.out.println("最后文件名:"+fileName);
File file = new File("D:/servletUpload/" + fileName);
if (file.exists()) {
long filesize = file.length(); // 文件的长度
File f1 = new File("D:/servletUpload/" + fileName);
FileInputStream is = new FileInputStream(f1);
int i;
byte[] b = new byte[(int) filesize];
while ((i = is.read(b)) != -1) {
response.getOutputStream().write(b);
}
} else {
response.getWriter().println("2:文件不存在");
}
}
}
public class Test {
public static void main(String[] args) throws Exception {
String uploadFileName = "d:\\第1章.pdf";
File file1 = new File(uploadFileName);
URL url = new URL("http://192.168.0.73:8080/cssServer_part/Upload");
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setDoOutput(true);// 打开写入属性
httpURLConnection.setDoInput(true);// 打开读取属性
httpURLConnection.setRequestMethod("POST");// 设置提交方法
httpURLConnection.setConnectTimeout(500000000);// 连接超时时间
httpURLConnection.setReadTimeout(500000000);
httpURLConnection.setRequestProperty("Accept", "*/*");
String boundary = "--------------------"
+ Long.toString(System.currentTimeMillis(), 16);
httpURLConnection.setRequestProperty("Content-Type",
"multipart/form-data;boundary=" + boundary); // 设置表单类型和分隔符
httpURLConnection.setRequestProperty("Connection", "Keep-Alive");
httpURLConnection.setRequestProperty("Cache-Control", "no-cache");
httpURLConnection.setRequestProperty("Content-Length", Long.toString(file1.length()));
httpURLConnection.setRequestProperty("FilePath", "D:/test/");
httpURLConnection.setRequestProperty("FileName", "第1章.pdf");
httpURLConnection.setRequestProperty("FileLength", "10240");
httpURLConnection.connect();
DataOutputStream dstream = new DataOutputStream(
httpURLConnection.getOutputStream());
FileInputStream fis1 = null;
fis1 = new FileInputStream(file1);
byte[] fileStuff = new byte[512];
int howMany = -1;
int totMany = 0;
howMany = fis1.read(fileStuff, 0, 512);
while (howMany != -1) {
totMany += howMany;
dstream.write(fileStuff, 0, howMany);
// System.out.println(new String(fileStuff));
howMany = fis1.read(fileStuff, 0, 512);
}
System.out.println("read " + totMany + " bytes from file, wrote to outputstream.");
fis1.close();
dstream.flush();
dstream.close();
// 读取post之后的返回值
BufferedReader in = new BufferedReader(new InputStreamReader(
(InputStream) httpURLConnection.getInputStream()));
String line = null;
StringBuilder sb = new StringBuilder();
while ((line = in.readLine()) != null) {
sb.append(line);
}
in.close();
System.out.println("client:" + sb.toString());
httpURLConnection.disconnect();// 断开连接
}
}
4.web.xml
<servlet>
<description>上传servlet</description>
<servlet-name>Upload</servlet-name>
<servlet-class>com.gx.servlet.Upload</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Upload</servlet-name>
<url-pattern>/Upload</url-pattern>
</servlet-mapping>
<servlet>
<description>下载servlet</description>
<servlet-name>Download</servlet-name>
<servlet-class>com.gx.servlet.Download</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Download</servlet-name>
<url-pattern>/Download</url-pattern>
</servlet-mapping>