这些日子我正在敲打这个问题,也许你肯定比我更了解你可以帮助我.... 然后我试着更好地解释。
我有一个javascript文件,通过库d3.js构建html代码页并将其替换为其他代码,每个部分都有不同的功能......该页面不会收费(Ajax)。 在某些时候我需要允许用户将图像上传到他们的个人资料图片,所以我确保html代码诱饵
<input type="file" id="file">
和
<input type = "button" onclick = "javaScript: performAjaxSubmit ()">
PerformAjaxSubmit function()通过xmlHttpRequest级别2将数据发送到Java Servlet,根据我的理解,这不仅可以发送字符串,还可以发送更复杂的文件等。
功能如下:
function performAjaxSubmit() {
var sampleFile = document.getElementById("file").files[0];
var formdata = new FormData();
formdata.append("sampleFile", sampleFile);
var xhr = new XMLHttpRequest();
xhr.open("POST", "http://127.0.0.1:8080/Prova/Upload", true);
xhr.send(formdata);
xhr.onload = function(e) {
if (this.status == 200) {
alert(this.responseText);
}
};
}
Servlet中的代码是:
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// Check that we have a file upload request
System.out.println(request.getAttribute("username"));
isMultipart = ServletFileUpload.isMultipartContent(request);
response.setContentType("text/html");
java.io.PrintWriter out = response.getWriter( );
DiskFileItemFactory factory = new DiskFileItemFactory();
// maximum size that will be stored in memory
factory.setSizeThreshold(maxMemSize);
// Location to save data that is larger than maxMemSize.
factory.setRepository(new File("C:/Users/Marty/workspaceJEE/Prova/WebContent/imm/utenti"));
filePath="C:/Users/Marty/workspaceJEE/Prova/WebContent/imm/utenti";
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// maximum file size to be uploaded.
upload.setSizeMax( maxFileSize );
try{
// Parse the request to get file items.
List fileItems = upload.parseRequest(request);
// Process the uploaded file items
Iterator i = fileItems.iterator();
while ( i.hasNext () )
{
FileItem fi = (FileItem)i.next();
if ( !fi.isFormField () )
{
// Get the uploaded file parameters
String fieldName = fi.getFieldName();
String fileName = fi.getName();
String contentType = fi.getContentType();
boolean isInMemory = fi.isInMemory();
long sizeInBytes = fi.getSize();
// Write the file
if( fileName.lastIndexOf("\\") >= 0 ){
file = new File( filePath +"/"+
fileName.substring( fileName.lastIndexOf("\\"))) ;
}else{
System.out.println(filePath +
fileName.substring(fileName.lastIndexOf("\\")+1));
file = new File( filePath +"/"+
fileName.substring(fileName.lastIndexOf("\\")+1)) ;
}
fi.write( file ) ;
}
}
}catch(Exception ex) {
System.out.println(ex);
}
}
现在(对不起,如果问题有点长)它可以工作,但问题是图像保存在我向我提供命令的路径中:
factory.setRepository(new File("C:/Users/Marty/workspaceJEE/Prova/WebContent/imm/utenti"));
如何远程保存?也就是说,一旦我加载了这样的Altrevista网站,我如何确保它们不是pià保存到C但是保存在项目的文件夹中?
我希望我解释一下。我正在使用Apache Tomcat v7.0。 提前谢谢!
答案 0 :(得分:0)
您可以使用ServletContext.getRealPath
此代码返回<context root>/upload
(取决于您的部署配置)
request.getSession().getServletContext().getRealPath("/upload")