在Java WebService中實現文件上傳可以使用以下步驟:
import javax.jws.WebMethod;
import javax.jws.WebService;
import javax.jws.WebParam;
@WebService
public class FileUploadService {
@WebMethod
public String uploadFile(@WebParam(name="fileName") String fileName, @WebParam(name="fileContent") byte[] fileContent) {
// 實現文件上傳邏輯
return "File uploaded successfully";
}
}
在Web Service類中實現文件上傳邏輯。可以使用Java IO類來將文件內容寫入到服務器上的指定路徑。
在web.xml文件中配置Servlet以處理文件上傳請求。可以使用Apache Commons FileUpload庫來解析上傳的文件數據。例如:
<servlet>
<servlet-name>FileUploadServlet</servlet-name>
<servlet-class>com.example.FileUploadServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FileUploadServlet</servlet-name>
<url-pattern>/fileUpload</url-pattern>
</servlet-mapping>
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import java.io.InputStream;
public class FileUploadServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) {
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List<FileItem> items = upload.parseRequest(request);
for (FileItem item : items) {
if (!item.isFormField()) {
InputStream fileContent = item.getInputStream();
byte[] buffer = new byte[fileContent.available()];
fileContent.read(buffer);
FileUploadService service = new FileUploadService();
String result = service.uploadFile(item.getName(), buffer);
// 返回上傳結果
response.getWriter().write(result);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}