如何将文件移至托管? 我使用此代码但它不起作用。
File uploads = new File("/Users/Aurimo/Desktop/");
File file = new File(request.getParameter("dataFile"));
file.renameTo(uploads);
答案 0 :(得分:0)
为了创建用于上传的jsp页面,您可以在文件系统中创建数据库,文件夹,显示上传表单,然后显示结果。以下链接对您有所帮助:
http://www.codejava.net/coding/upload-files-to-database-servlet-jsp-mysql http://www.tutorialspoint.com/jsp/jsp_file_uploading.htm
答案 1 :(得分:0)
use multipart form
and server side use following code.
for(FileItem item : multiparts){
if(!item.isFormField()){
String name = new File(item.getName()).getName();
item.write( new File(UPLOAD_DIRECTORY + File.separator + name));
request.setAttribute("photoname", name);
}else{
// here get value of other parameter which is not file type
System.out.println(item.getFieldName()+" = "+item.getString());
}
}
答案 2 :(得分:0)
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
List<FileItem> items = upload.parseRequest(request);
for (FileItem item : items) {
if (item.isFormField()) { //als het een veld is dan dit, anders File uploaden
String fieldname = item.getFieldName();
String fieldvalue = item.getString();
switch (fieldname) {
case "logicalName":
LogicalName = fieldvalue;
break;
//other case statements...
}
} else {
//here you only have to process the file
File file;
int maxFileSize = 500000 * 1024;//your comments...
int maxMemSize = 5000 * 1024;//your comments...
//this must be a constant or a servlet init param, do not hard code it
String filePath = "C:\\uploads\\";
String fileName = FilenameUtils.getName(item.getName());
factory.setSizeThreshold(maxMemSize);
//didn't you have a filePath variable?
factory.setRepository(new File("c:\\temp"));
upload.setSizeMax(maxFileSize);
try {
String fieldName = fi.getFieldName();
boolean isInMemory = fi.isInMemory();
long sizeInBytes = fi.getSize();
file = new File(filePath, fileName);
item.write(file);
//code to save your file location in db...
//note: this MUST BE in a business logic method, not directly written in your servlet
HttpSession session = request.getSession();
int uploader = (Integer) session.getAttribute("UserId");
} catch (Exception ex) {
//very BAD idea
//use a logger instead like log4j or sfl4j
System.out.println(ex);
}
}
}