我正在尝试使用
在JSP中上传文件<form action="EdgeWarUpload" method="post"
enctype="multipart/form-data">
<input type="file" name="file" size="50" />
<br />
<input type="submit" value="Upload File" />
其中EdgeWarUpload是一个servlet.User正在浏览并选择要上传的文件。我希望在servlet EdgeWarUpload中使用带有文件名(路径名+文件名)的完全限定路径来创建BufferedInputStream.But我无法获得它。亲切地检查并回复。
答案 0 :(得分:1)
<html>
<header></header>
<body>
<form method="POST" action="upload.do">
escolha o arquivo para fazer upload:
<input type="file" name="ctrupload"><br>
<input type="submit" name="submit" value="enviar...">
</form>
</body>
</html>
试试这个
public class Uploader extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
ServletInputStream sis = request.getInputStream();
byte[] b = new byte[request.getContentLength()];
System.out.println(request.getContentLength());
sis.read(b,0,b.length);
FileOutputStream fos = new FileOutputStream("Teste.jpg");
fos.write(b);
sis.close();
fos.flush();
fos.close();
}
}
你真的不需要完全合格的路径
答案 1 :(得分:0)
绝大多数都不可能。
浏览器不会发送完整路径,因为它被认为是安全风险,因为它可能会告诉客户端系统,所以大多数现代浏览器都支持它。
在服务器端没有使用我猜。只需使用filename
。
答案 2 :(得分:0)
这里你可以在servlet中使用这段代码来获取文件名:
DataInputStream in = new DataInputStream(request.getInputStream());
int formDataLength = request.getContentLength();
byte dataBytes[] = new byte[formDataLength];
int byteRead = 0;
int totalBytesRead = 0;
while (totalBytesRead < formDataLength) {
byteRead = in.read(dataBytes, totalBytesRead, formDataLength);
totalBytesRead += byteRead;
}
String file = new String(dataBytes);
saveFile = file.substring(file.indexOf("filename=\"") + 10);
saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1, saveFile.indexOf("\""));
System.out.println("filename3: "+ saveFile); // name of the file
int lastIndex = contentType.lastIndexOf("=");
String boundary = contentType.substring(lastIndex + 1, contentType.length());
int pos;
pos = file.indexOf("filename=\"");
pos = file.indexOf("\n", pos) + 1;
pos = file.indexOf("\n", pos) + 1;
pos = file.indexOf("\n", pos) + 1;
int boundaryLocation = file.indexOf(boundary, pos) - 4;
int startPos = ((file.substring(0, pos)).getBytes()).length;
int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;
FileOutputStream fileOut = new FileOutputStream(saveFile);
fileOut.write(dataBytes, startPos, (endPos - startPos));
fileOut.flush();
fileOut.close();
FileInputStream fis = new FileInputStream(saveFile);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] buf = new byte[1024];
for (int readNum; (readNum = fis.read(buf)) != -1;) {
bos.write(buf, 0, readNum);
}
byte[] bytes = bos.toByteArray();
bos.close();
fis.close();
in.close();