How to Customize Aliyun OSS File Upload Configuration in the Mall Project
All Aliyun OSS upload settings in the Mall e-commerce project are externalized in application.yml under the aliyun.oss prefix and injected into the upload flow via Spring beans, allowing you to change endpoints, credentials, bucket names, and upload policies without modifying Java code.
The macrozheng/mall project uses Aliyun OSS (Object Storage Service) as its default file storage solution for handling product images and other media assets. This Spring Boot application centralizes every OSS-related property in a single configuration file, making it straightforward to customize the file upload configuration for different environments or storage requirements. Whether you need to switch regions, increase file size limits, or redirect upload callbacks, the system is designed for zero-code configuration changes.
Centralized Configuration in application.yml
The primary source for Aliyun OSS file upload configuration resides in mall-admin/src/main/resources/application.yml. All properties are grouped under the aliyun.oss namespace:
aliyun:
oss:
endpoint: oss-cn-shenzhen.aliyuncs.com
accessKeyId: test
accessKeySecret: test
bucketName: macro-oss
policy:
expire: 300
maxSize: 10
callback: http://yourhost/aliyun/oss/callback
dir:
prefix: mall/images/
Key properties you can modify to customize the upload behavior include:
endpoint– The OSS region endpoint (e.g.,oss-cn-hangzhou.aliyuncs.com). Change this to match the physical region where your bucket is located.accessKeyIdandaccessKeySecret– Your Alibaba Cloud RAM credentials. The system uses these to generate signed upload URLs. Never commit production secrets to version control; use environment-specific overrides instead.bucketName– The target storage bucket. Update this to point to your own OSS bucket.policy.expire– Signature validity window in seconds (default 300). Decrease for tighter security or increase for slower networks.maxSize– Maximum single-file upload size in megabytes. Adjust this to accommodate larger product images or videos.callback– The URL that Aliyun OSS will POST to after a successful upload. Modify this to point to your custom notification endpoint.dir.prefix– The virtual folder path inside the bucket where files are stored. Change this to organize uploads (e.g.,products/2024/).
Spring Boot automatically binds these values to the corresponding Java components at runtime using @Value annotations.
Wiring the OSS Client Bean
The OssConfig class in mall-admin/src/main/java/com/macro/mall/config/OssConfig.java constructs the primary OSSClient instance using the endpoint and credential properties:
@Configuration
public class OssConfig {
@Value("${aliyun.oss.endpoint}")
private String ALIYUN_OSS_ENDPOINT;
@Value("${aliyun.oss.accessKeyId}")
private String ALIYUN_OSS_ACCESSKEYID;
@Value("${aliyun.oss.accessKeySecret}")
private String ALIYUN_OSS_ACCESSKEYSECRET;
@Bean
public OSSClient ossClient(){
return new OSSClient(ALIYUN_OSS_ENDPOINT, ALIYUN_OSS_ACCESSKEYID, ALIYUN_OSS_ACCESSKEYSECRET);
}
}
When you modify endpoint, accessKeyId, or accessKeySecret in application.yml and restart the mall-admin service, Spring instantiates a new OSSClient bean with the updated parameters. This client is then autowired into the upload service layer.
Generating Signed Upload Policies
The OssServiceImpl class handles server-side policy generation for browser-based uploads. Located at mall-admin/src/main/java/com/macro/mall/service/impl/OssServiceImpl.java, this service reads the remaining configuration values to construct a secure upload policy:
@Value("${aliyun.oss.policy.expire}")
private int ALIYUN_OSS_EXPIRE;
@Value("${aliyun.oss.maxSize}")
private int ALIYUN_OSS_MAX_SIZE;
@Value("${aliyun.oss.callback}")
private String ALIYUN_OSS_CALLBACK;
@Value("${aliyun.oss.bucketName}")
private String ALIYUN_OSS_BUCKET_NAME;
@Value("${aliyun.oss.endpoint}")
private String ALIYUN_OSS_ENDPOINT;
@Value("${aliyun.oss.dir.prefix}")
private String ALIYUN_OSS_DIR_PREFIX;
The policy() method constructs a Base64-encoded policy document that enforces:
- The allowed key prefix (derived from
ALIYUN_OSS_DIR_PREFIXand the current date). - The maximum file size constraint (
maxSize). - The expiration timestamp (
expire). - The callback URL configuration.
It returns an OssPolicyResult DTO containing the fields required for a direct browser upload:
accessKeyId– The credential identifier.policy– The Base64-encoded policy string.signature– The cryptographic signature verifying the policy.dir– The computed directory prefix the client must use.host– The target upload URL constructed ashttp://{bucketName}.{endpoint}.callback– Base64-encoded callback configuration.
Changes to maxSize, policy.expire, or dir.prefix in application.yml are immediately reflected in the next policy request without requiring a code recompilation.
Exposing the Policy Endpoint
The OssController in mall-admin/src/main/java/com/macro/mall/controller/OssController.java exposes the policy to the frontend via a REST endpoint:
@RequestMapping(value = "/policy", method = RequestMethod.GET)
@ResponseBody
public CommonResult<OssPolicyResult> policy() {
OssPolicyResult result = ossService.policy();
return CommonResult.success(result);
}
When a client calls GET /aliyun/oss/policy, the controller returns the signed parameters that authorize the browser to upload directly to Aliyun OSS. This decouples your backend from handling the actual file bytes, reducing bandwidth and server load.
Handling Upload Callbacks
After a successful upload, Aliyun OSS sends a notification to the URL specified in aliyun.oss.callback. The OssServiceImpl.callback() method processes this request:
public OssCallbackResult callback(HttpServletRequest request) {
// Translates OSS parameters into OssCallbackResult
}
The controller endpoint at /aliyun/oss/callback receives the POST request from OSS and delegates to this service method. To customize callback behavior—such as validating the request origin or persisting metadata to a database—modify the callback property in application.yml to point to your custom endpoint, or extend the logic within OssServiceImpl.callback().
Step-by-Step Customization Guide
To apply a custom Aliyun OSS file upload configuration in your Mall deployment:
- Edit
mall-admin/src/main/resources/application.ymland update thealiyun.ossproperties with your actual Alibaba Cloud credentials, bucket name, and preferred region endpoint. - Adjust upload constraints by modifying
maxSize(in MB) andpolicy.expire(in seconds) to match your security and usability requirements. - Configure the callback URL to point to a publicly accessible endpoint in your infrastructure, or disable callbacks by leaving the value empty if not needed.
- Organize file storage by changing
dir.prefixto logically separate uploads (e.g.,uploads/avatars/orinventory/photos/). - Restart the
mall-adminservice to reload the Spring context. The application will instantiate a newOSSClientand begin issuing policies with the updated parameters.
This externalized configuration approach ensures that sensitive credentials remain outside your source code while allowing environment-specific overrides using Spring profiles (e.g., application-prod.yml).
Summary
- Configuration source: All OSS settings live in
mall-admin/src/main/resources/application.ymlunder thealiyun.ossprefix. - Client instantiation:
OssConfig.javacreates theOSSClientbean from endpoint and credential properties. - Policy generation:
OssServiceImpl.javabuilds signed upload policies using@Value-injected configuration values for expiration, size limits, and directory prefixes. - Zero-code changes: Most customizations—region, bucket, credentials, upload limits—require only YAML edits and a service restart.
- Callback handling: The
callbackproperty controls where OSS posts upload confirmations, processed byOssServiceImpl.callback().
Frequently Asked Questions
How do I switch to a different Aliyun OSS region?
Change the aliyun.oss.endpoint value in application.yml to your target region's endpoint (e.g., oss-cn-beijing.aliyuncs.com). Ensure the bucketName corresponds to a bucket created in that same region, then restart the mall-admin service. The OssConfig.java bean will automatically instantiate a new client pointing to the updated endpoint.
Where should I store my AccessKey credentials securely?
Never commit real accessKeyId or accessKeySecret values to version control. Instead, use Spring Boot's externalized configuration features: set them as environment variables (ALIYUN_OSS_ACCESSKEYID) or use a separate application-prod.yml file that is excluded from Git. Spring will resolve ${} placeholders or standard env vars in the YAML file at runtime.
How do I increase the maximum file upload size?
Modify the aliyun.oss.maxSize property in application.yml to the desired value in megabytes (e.g., 50 for 50MB). The OssServiceImpl.policy() method injects this value into the generated policy document, and OSS will reject uploads exceeding this limit at the edge before they reach your servers.
Can I disable the upload callback notification?
Yes. To disable callbacks, remove or comment out the aliyun.oss.callback property in application.yml, or set it to an empty string. Without a callback URL, Aliyun OSS will not attempt to POST to your server after uploads, and the OssController.callback() endpoint will not be triggered by OSS events.
Have a question about this repo?
These articles cover the highlights, but your codebase questions are specific. Give your agent direct access to the source. Share this with your agent to get started:
curl -s "https://instagit.com/install.md" Maintain an open-source project? Get it listed too →