【发布时间】:2018-06-14 12:35:18
【问题描述】:
当我从 Mozilla 浏览器将文件上传到本地系统的临时目录时,我收到拒绝访问错误。但是如果我从 Eclipse 浏览器做同样的事情,我没有看到任何错误,这意味着它正在上传而没有任何错误:
代码:
for (Part part : request.getParts()) {
fileName = getFileName(part);
part.write(System.getProperty("java.io.tmpdir") + fileName);
}
private String getFileName(Part part) {
String contentDisp = part.getHeader("content-disposition");
System.out.println("content-disposition header= "+contentDisp);
String[] tokens = contentDisp.split(";");
for (String token : tokens) {
if (token.trim().startsWith("filename")) {
return token.substring(token.indexOf("=") + 2, token.length()-1);
}
}
return "";
错误:
java.io.IOException: java.io.FileNotFoundException: C:\Users\user\AppData\Local\Temp (Access is denied)
艾伦,这是代码:
final String path = System.getProperty("java.io.tmpdir");
OutputStream out = null;
InputStream filecontent = null;
final PrintWriter writer = response.getWriter();
try {
for (Part part : request.getParts()) {
String fileName = getFileName(part);
out = new FileOutputStream(new File(path , fileName));
filecontent = part.getInputStream();
int read = 0;
final byte[] bytes = new byte[1024];
while ((read = filecontent.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
File UploadedFile = new File(path + File.separator + fileName);
UploadedFile.delete();
}
} catch (FileNotFoundException fne) {
writer.println("You either did not specify a file to upload or are "
+ "trying to upload a file to a protected or nonexistent "
+ "location.");
} finally {
if (out != null) {
out.close();
}
if (filecontent != null) {
filecontent.close();
}
if (writer != null) {
writer.close();
}
}
【问题讨论】:
-
感谢 Allan 提供参考问题,但我的问题是,它是一个网络应用程序,因此任何人都可以使用。任何人如何获得对用户临时文件夹的访问权限(根据 Sircapsalot 的解决方案)。如果我的理解不正确,请告诉我。
-
您可以尝试使用 createTempDirectory 类在另一个路径中创建。
-
文件 myTempDir = Files.createTempDir();
-
尝试使用“File myTempDir = Files.createTempDir()”,我再次看到同样的错误访问被拒绝
标签: java