servlet3.0的学习(三)

[size=large]文件的上传[/size]
Upload.java
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.UUID;
import javax.servlet.ServletConfig;
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 javax.servlet.http.Part;


@WebServlet(urlPatterns = {"/upload"})
public class Upload extends HttpServlet {

@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
}

@Override
protected void service(HttpServletRequest req, HttpServletResponse res)
throws IOException, ServletException {

PrintWriter out = res.getWriter();
InputStream is = null;
FileOutputStream fos = null;
String targetDirectory = req.getServletContext().getRealPath("/upload");
try {
for (Part p : req.getParts()) {
UUID id = UUID.randomUUID();
out.write("Part name: " + p.getName() + "<br/>\n");
out.write("Size: " + p.getSize() + "<br/>\n");
out.write("Content Type: " + p.getContentType() + "<br/>\n");
is = p.getInputStream();


File file = new File(targetDirectory, id.toString() + ".jpg");
fos = new FileOutputStream(file);
out.write("Header Names:");
for (String name : p.getHeaderNames()) {
out.write(" " + name);
}
out.write("<br/><br/>\n");

while (true) {
int bytedata = is.read();
if (bytedata == '\n') out.write("<br/>");
if (bytedata == -1) {
break;

}
fos.write(bytedata);
}

}
} finally {
if (is != null) {
is.close();

}
if (out != null) {
out.close();

}
}
}
}


index.html
<html>
<head>
<title>File Upload Example</title>
</head>

<body>
<form action="upload" method="post"
enctype="multipart/form-data">
<h3>Choose files to upload.</h3>
<input name="myFile" type="file" /> <br/>
<input name="myFile2" type="file"/> <br/> <br/>
<input value="upload" type="submit"/>
<input type="reset"/> <br/>
</form>
</body>
</html>


讲解:javax.servlet.http.Interface Part,这个接口主要是用来接收提交形式为multipart/form-data POST 请求.
void delete() :删除一个文件项目的底层存储,包括删除任何相关的临时磁盘文件
java.lang.String getContentType():获取内容类型,如image/x-png,
application/octet-stream
java.lang.String getHeader(java.lang.String name):返回指定的MIME头
java.util.Collection<java.lang.String> getHeaderNames():获取本部分的头名。
java.io.InputStream getInputStream():返回当前文件的输入流
java.lang.String getName():获取文件名,input的name
long getSize():获取大小
void write(java.lang.String fileName):写入本地硬盘,如果有多个文件需要保存时次方法并不能保证成功
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值