【发布时间】:2015-11-10 09:09:16
【问题描述】:
我正在开发网络应用程序,需要为用户上传文件。上传文件夹在 web 应用程序 之外 - 在 openstack 数据文件夹中(在standalone.xml 中设置) - 示例:
<host name="default-host" alias="localhost">
<location name="/" handler="welcome-content"/>
<location name="/folder" handler="folder"/>
<filter-ref name="server-header"/>
<filter-ref name="x-powered-by-header"/>
</host>
...
<handlers>
<file name="welcome-content" path="${jboss.home.dir}/welcome-content"/>
<file name="folder" path="/absolute/path/on/server" directory-listing="true"/>
</handlers>
如果我需要访问这些文件,没有问题(我只需键入 mydomain.com/folder/xyz.jpg),但是我需要从 Java 代码中引用该文件夹(获取文件夹的路径,然后由用户上传文件)。我的用于上传的 Java REST 接口如下所示:
public class DictateUploadResource {
public static final String UPLOADED_FILE_PARAMETER_NAME = "file";
private final String UPLOAD_DIR = servletContext.getRealPath("/folder");
@POST
@Consumes("multipart/form-data")
public Response uploadFile(MultipartFormDataInput input) {
String path = servletContext.getRealPath("/folder");
LOGGER.warn(">>>> sit back - starting file upload..." + path);
Map<String, List<InputPart>> uploadForm = input.getFormDataMap();
List<InputPart> inputParts = uploadForm.get(UPLOADED_FILE_PARAMETER_NAME);
for (InputPart inputPart : inputParts) {
MultivaluedMap<String, String> headers = inputPart.getHeaders();
String filename = getFileName(headers);
try {
InputStream inputStream = inputPart.getBody(InputStream.class, null);
byte[] bytes = IOUtils.toByteArray(inputStream);
LOGGER.info(">>> File '{}' has been read, size: #{} bytes", filename, bytes.length);
writeFile(bytes, path + "/" + filename);
} catch (IOException e) {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(e.getMessage()).build();
}
}
return Response.status(Response.Status.OK).build();
}
/**
* Build filename local to the server.
*
* @param filename
* @return
*/
private String getServerFilename(String path, String filename) {
return path + "/" + filename;
}
private void writeFile(byte[] content, String filename) throws IOException {
LOGGER.info(">>> writing #{} bytes to: {}", content.length, filename);
File file = new File(filename);
if (!file.exists()) {
file.createNewFile();
}
FileOutputStream fop = new FileOutputStream(file);
fop.write(content);
fop.flush();
fop.close();
LOGGER.info(">>> writing complete: {}", filename);
}
/**
* Extract filename from HTTP heaeders.
*
* @param headers
* @return
*/
private String getFileName(MultivaluedMap<String, String> headers) {
String[] contentDisposition = headers.getFirst("Content-Disposition").split(";");
for (String filename : contentDisposition) {
if ((filename.trim().startsWith("filename"))) {
String[] name = filename.split("=");
String finalFileName = sanitizeFilename(name[1]);
return finalFileName;
}
}
return "unknown";
}
private String sanitizeFilename(String s) {
return s.trim().replaceAll("\"", "");
}
}
提前致谢!
【问题讨论】:
-
“别名在standalone.xml中设置”是什么意思?
-
我将问题编辑得更清楚:)