我正在开发一个java项目,我在eclipse下有一个动态的web项目,接收请求和处理文件上传,现在一切都还可以,但我想存储上传的文件,以便能够托管我的文件,例如,当我把这个样本网址录下来时,我想要那个:
本地主机:18080 /上传/ img.jpg
在浏览器中我可以看到屏幕上的图像。 这就是我所拥有的项目结构: project structure我有一个REST资源,我没有使用servlet级别,我的应用程序部署在wildfly而不是tomcat,
这里我的Rest资源向您展示代码:
package rest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.List;
import java.util.Map;
import javax.faces.bean.RequestScoped;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.Response;
import sun.misc.IOUtils;
import org.jboss.resteasy.plugins.providers.multipart.InputPart;
import org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataInput;
@RequestScoped
@Path("uploader")
public class UploadResource {
private final String UPLOADED_FILE_PATH = "d:\\";
@POST
@Path("/upload")
@Consumes("multipart/form-data")
@Produces(MediaType.APPLICATION_JSON)
public UploadResponse uploadFile(MultipartFormDataInput input)
throws URISyntaxException {
String fileName = "";
UploadResponse uploadResponse = null;
Map<String, List<InputPart>> uploadForm = input.getFormDataMap();
List<InputPart> inputParts = uploadForm.get("uploadedFile");
for (InputPart inputPart : inputParts) {
MultivaluedMap<String, String> header = inputPart.getHeaders();
fileName = getFileName(header);
// convert the uploaded file to inputstream
InputStream inputStream;
try {
inputStream = inputPart.getBody(InputStream.class, null);
byte[] bytes = IOUtils.readFully(inputStream, 0, false);
fileName = UPLOADED_FILE_PATH + fileName;
uploadResponse = new UploadResponse(fileName);
writeFile(bytes, fileName);
System.out.println("Done");
} catch (IOException e) {
e.printStackTrace();
}
}
return uploadResponse;
}
private void writeFile(byte[] content, String fileName) throws IOException {
String url = this.getClass().getResource("/slide-1.jpg").toString();
System.out.println("url" + url);
/*
* URL url = this.getClass().getResource("/"); System.out.println("url"
* + url); File fullPathToSubfolder = new File(url.toURI())
* .getAbsoluteFile(); String projectFolder =
* fullPathToSubfolder.getAbsolutePath() .split("target")[0]; fileName =
* projectFolder + "WebContent/uploads/resources/";
*/
File file = new File(fileName);
if (!file.exists()) {
file.createNewFile();
}
FileOutputStream fop = new FileOutputStream(file);
fop.write(content);
fop.flush();
fop.close();
}
private String getFileName(MultivaluedMap<String, String> header) {
String[] contentDisposition = header.getFirst("Content-Disposition")
.split(";");
for (String filename : contentDisposition) {
if ((filename.trim().startsWith("filename"))) {
String[] name = filename.split("=");
String finalFileName = name[1].trim().replaceAll("\"", "");
return finalFileName;
}
}
return "unknown";
}
}
请帮助我,我对此问题感到困惑。