我已经使用servlet3.0编写了一个用于上传文件的servlet,它可以很好地上传文件。但我想以客户端上传的格式将文件保存在服务器中。
Part filePart = request.getPart("chosenFile");
String filename = new SimpleDateFormat("yyyyMMddhhmmss").format(new Date()).toString();
System.out.println(filePart.getContentType().split("/")[1]);
InputStream inputStream =null;
OutputStream outputStream =null;
File fileSaveDirectory = new File(UPLOAD_DIR);
if(!fileSaveDirectory.exists()){
fileSaveDirectory.mkdir();
}
String content_path = UPLOAD_DIR+File.separator+filename;//earlier
//here I was appending the string ".pdf" to every file
//but now I want the file type to be the uploaded file type.
//say if user uploads in .jpeg or any other.
System.out.println("Content Path : "+content_path);
outputStream = new FileOutputStream(new File(content_path));
inputStream = filePart.getInputStream();
int read=0;
while((read=inputStream.read())!=-1){
outputStream.write(read);
}
if(outputStream!=null)
outputStream.close();
if(inputStream !=null)
inputStream.close();
如何保留文件类型,上传文件的类型。请帮忙 !!!
答案 0 :(得分:0)
请参阅@ http://docs.oracle.com/javaee/6/tutorial/doc/glraq.html:
private String getFileName(final Part part) {
final String partHeader = part.getHeader("content-disposition");
LOGGER.log(Level.INFO, "Part Header = {0}", partHeader);
for (String content : part.getHeader("content-disposition").split(";")) {
if (content.trim().startsWith("filename")) {
return content.substring(
content.indexOf('=') + 1).trim().replace("\"", "");
}
}
return null;
}
因此,当您的(文件上传)请求设置正常/正常时,(http)标头content-disposition
将包含;
filename
<?php
class DatabaseTest extends PHPUnit_Framework_TestCase
{
protected static $dbh;
public static function setUpBeforeClass()
{
self::$dbh = new PDO('sqlite::memory:');
}
public static function tearDownAfterClass()
{
self::$dbh = NULL;
}
}
?>
属性(以及其他内容),您可以使用(在整个或中)提取文件后缀。