Weblogic 12c环境下单PDF文件上传下载实现方案咨询
Alright, let's put together a complete, working implementation for your PDF upload/download feature—since you already have a Direct-Write File Store set up in Weblogic 12c, we'll build on that with Java 7 backend code and AngularJS frontend. Here's how to do it step by step:
1. Backend Java (Servlet) Setup
We'll use two servlets: one for handling PDF downloads, another for accepting uploads to replace the existing file. Note that Java 7 (paired with Java EE 6) doesn't have built-in multipart file support, so we'll use Apache Commons FileUpload for upload handling.
1.1 First, Add Dependencies
Download these JARs and place them in your web app's WEB-INF/lib folder:
commons-fileupload-1.4.jarcommons-io-2.11.0.jar(compatible with Java 7)
1.2 Download Servlet
This servlet streams the stored PDF to the user's browser for download:
import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.*; @WebServlet("/downloadPdf") public class PdfDownloadServlet extends HttpServlet { // Replace this with your Direct-Write File Store's physical directory path private static final String PDF_STORAGE_PATH = "/opt/weblogic/filestores/direct-write-store"; private static final String STORED_PDF_NAME = "current-document.pdf"; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { File pdfFile = new File(PDF_STORAGE_PATH, STORED_PDF_NAME); if (!pdfFile.exists()) { response.sendError(HttpServletResponse.SC_NOT_FOUND, "No PDF available for download"); return; } // Configure response headers for PDF download response.setContentType("application/pdf"); response.setHeader("Content-Disposition", "attachment; filename=\"" + STORED_PDF_NAME + "\""); response.setContentLength((int) pdfFile.length()); // Stream the file to the response try (InputStream inputStream = new FileInputStream(pdfFile); OutputStream outputStream = response.getOutputStream()) { byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } } } }
1.3 Upload Servlet
This servlet accepts a PDF upload, validates it, and replaces the existing stored file:
import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.IOException; import java.util.List; @WebServlet("/uploadPdf") public class PdfUploadServlet extends HttpServlet { private static final String PDF_STORAGE_PATH = "/opt/weblogic/filestores/direct-write-store"; private static final String STORED_PDF_NAME = "current-document.pdf"; private static final String ALLOWED_EXTENSION = "pdf"; protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Validate request is multipart if (!ServletFileUpload.isMultipartContent(request)) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Request must be multipart/form-data"); return; } DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); try { List<FileItem> items = upload.parseRequest(request); for (FileItem item : items) { if (!item.isFormField()) { String fileName = item.getName(); // Validate file type if (!fileName.toLowerCase().endsWith("." + ALLOWED_EXTENSION)) { response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Only PDF files are allowed"); return; } // Replace existing file File targetFile = new File(PDF_STORAGE_PATH, STORED_PDF_NAME); item.write(targetFile); response.setStatus(HttpServletResponse.SC_OK); response.getWriter().write("PDF uploaded and replaced successfully"); return; } } response.sendError(HttpServletResponse.SC_BAD_REQUEST, "No file was selected for upload"); } catch (FileUploadException e) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Upload failed: " + e.getMessage()); } catch (Exception e) { response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Failed to save file: " + e.getMessage()); } } }
2. Frontend AngularJS Implementation
We'll create a simple controller and template to handle the user interactions:
2.1 HTML Template
<div ng-controller="PdfManagerController"> <button ng-click="triggerDownload()" class="btn btn-primary">Download Current PDF</button> <br><br> <input type="file" id="pdfUploadInput" accept=".pdf" /> <button ng-click="uploadNewPdf()" class="btn btn-success">Upload & Replace PDF</button> <div ng-if="statusMessage" class="mt-3 alert alert-info">{{statusMessage}}</div> </div>
2.2 AngularJS Controller
angular.module('yourAppModule').controller('PdfManagerController', ['$scope', '$http', '$window', function($scope, $http, $window) { // Replace with your web app's context path const APP_CONTEXT = '/your-web-app-context'; $scope.triggerDownload = function() { // Open download link in a new tab to trigger browser download $window.open(`${APP_CONTEXT}/downloadPdf`, '_blank'); }; $scope.uploadNewPdf = function() { const fileInput = document.getElementById('pdfUploadInput'); const selectedFile = fileInput.files[0]; if (!selectedFile) { $scope.statusMessage = "Please select a PDF file first"; return; } if (selectedFile.type !== 'application/pdf') { $scope.statusMessage = "Only PDF files are supported"; return; } const formData = new FormData(); formData.append('pdfFile', selectedFile); $http.post(`${APP_CONTEXT}/uploadPdf`, formData, { transformRequest: angular.identity, headers: {'Content-Type': undefined} }).then(function(response) { $scope.statusMessage = response.data; fileInput.value = ''; // Reset file input after successful upload }, function(error) { $scope.statusMessage = error.data || "Upload failed. Please try again."; }); }; }]);
3. Weblogic Configuration Checks
Since you already have a Direct-Write File Store, double-check these details:
- Confirm the Physical Directory path of your File Store and replace the
PDF_STORAGE_PATHvalues in both servlets with this path. - If Weblogic's security policy blocks file access, add this permission to your domain's
weblogic.policyfile:grant codeBase "file:/path/to/your/webapp/WEB-INF/lib/-" { permission java.io.FilePermission "/opt/weblogic/filestores/direct-write-store/-", "read,write"; }; - Ensure your web app is deployed with Servlet 3.0 support (Weblogic 12c defaults to this, so
@WebServletannotations will work without manualweb.xmlmappings).
4. Testing Steps
- Initial Download Test: Deploy your app, then visit
http://your-weblogic-server:port/your-web-app-context/downloadPdf—you'll get a 404 until you upload your first PDF. - Upload Test: Use the frontend upload button to select a local PDF. Check the status message for success.
- Verify Replacement: Download the PDF again to confirm it's the new file you uploaded.
- Troubleshooting: Check Weblogic's server logs (
domain_home/servers/your-server/logs/your-server.log) for any file permission or path errors.
内容的提问来源于stack exchange,提问作者Ellone

