我使用Jersey API来使用多部分数据(照片),我喜欢保存服务器应用程序目录而不是任何其他驱动器。我成功保存在任何其他驱动器中,如D驱动器,但无法找到将其保存在服务器应用程序目录中的方法。
@POST
@Path("uploadphoto")
@Consumes(MediaType.MULTIPART_FORM_DATA)
@Produces("text/plain")
public String uploadNotices(@FormDataParam("file") InputStream uploadedInputStream) {
String uploadedFileLocation = "d:/1.jpg";
// save it
try {
writeToFile(uploadedInputStream, uploadedFileLocation);
} catch(Exception e) {
return "no";
}
return "yes";
}
// save uploaded file to new location
private void writeToFile(InputStream uploadedInputStream, String uploadedFileLocation) throws Exception {
OutputStream out = new FileOutputStream(new File(uploadedFileLocation));
int read = 0;
byte[] bytes = new byte[1024];
out = new FileOutputStream(new File(uploadedFileLocation));
while ((read = uploadedInputStream.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
out.flush();
out.close();
}
答案 0 :(得分:1)
它解决了我的问题
@Context
private ServletContext context;
String filePath = context.getRealPath("images/");
File file = new File(filePath);
答案 1 :(得分:0)
您的jersey Web应用程序在服务器上的JVM(如Tomcat)中运行。应用程序的根文件路径通常是Tomcat服务器的文件夹。要获取此文件夹路径,您可以轻松执行以下操作:
String sRootPath = new File("").getAbsolutePath();
您可以使用根文件夹或您创建的任何其他自定义文件夹。试试这个,希望它有效。
答案 2 :(得分:0)
例如,您应该将这些文件保存在System.getProperty("java.io.tmpdir")
中,这是指定用于临时文件的文件。